ES6对象字面量中this的绑定问题及解决方法咨询
Ah, I see the issue here—arrow functions and object methods don't play nice when it comes to this binding, and it's a super common gotcha when moving from ES5 to ES6. Let's unpack this step by step.
First, remember that arrow functions don't have their own this context. Instead, they inherit this from the lexical scope where they're defined. In your IIFE (the self-executing function), the outer this is either window (in non-strict mode) or undefined (in strict mode)—so when you use arrow functions as methods on your navigation object, this never points to the object itself, which is why your code isn't working as expected.
The fix is straightforward: don't use arrow functions to define object methods. ES6 gave us a cleaner syntax for object methods that behaves exactly like the ES5 function expressions you're used to. Here's how your code should look:
(function() { const navigation = { // ES6 method shorthand (equivalent to init: function() {}) init() { console.log(this); // Now this correctly points to navigation! this.cacheDom(); this.bindEvents(); }, cacheDom() { this.$nav = $('nav'); this.$hamburger = $('button.ham'); }, bindEvents() { // Use an arrow function here if you want to inherit this from bindEvents() // which points to navigation—no need for .bind(this) anymore! this.$hamburger.click(() => this.toggleNav()); // Alternatively, if you prefer .bind() that works too: // this.$hamburger.click(this.toggleNav.bind(this)); }, toggleNav() { this.$nav.toggleClass('active'); } }; navigation.init(); })();
Key Notes:
- The method shorthand (
init() {}) preserves thethisbinding you expect: when you callnavigation.init(),thisinsideinitrefers to thenavigationobject. - For event handlers, arrow functions are actually useful here! Since they inherit
thisfrom the surroundingbindEvents()method (which isnavigation), you don't need to use.bind(this)to preserve the context. - If you ever try to reuse the
navigationobject (e.g., assign it to another variable likeconst nav = navigationand callnav.init()),thiswill still correctly point to the object being called—something you lose if you hardcode references tonavigationdirectly (like your original ES6 attempt).
内容的提问来源于stack exchange,提问作者user6347891

