You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the this binding you expect: when you call navigation.init(), this inside init refers to the navigation object.
  • For event handlers, arrow functions are actually useful here! Since they inherit this from the surrounding bindEvents() method (which is navigation), you don't need to use .bind(this) to preserve the context.
  • If you ever try to reuse the navigation object (e.g., assign it to another variable like const nav = navigation and call nav.init()), this will still correctly point to the object being called—something you lose if you hardcode references to navigation directly (like your original ES6 attempt).

内容的提问来源于stack exchange,提问作者user6347891

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:14:02