javascript - JS 对象字面量,this 上下文发生变化

标签 javascript function event-handling

我正在改进我的 Javascript 结构并尝试找出我喜欢的模式,我有以下内容:

var aThing = (function() {

  var module;

  return {

    init: function() {
      module = this;
      console.log(module);
    },

  };

})();

当我运行aThing.init();时,它会记录Object {init: function},这就是我想要的,当我做这样的事情时就会出现问题:

document.addEventListener('click', aThing.init, false);

这会记录#document。当我运行不带括号的函数时,this 似乎正在发生变化,但我不知道为什么。

最佳答案

这都是关于执行上下文的。尽管您的 init 方法位于 aThing 模块内,但您在其他地方执行它,因此您使用的“this”关键字将引用执行上下文。

您应该考虑利用您的模块来处理该事件,而不是在模块外部编写事件处理程序。它可以从模块的 init 方法内部完成,这将为您提供一个更清晰的结构,因为您将有关模块的所有内容都存储在模块本身内部,而不是在模块外部执行某些操作并在模块内部执行其他操作。

见下文:

var aThing = (function() {

  var module;

  return {
    
    init: function() {
      module = this;

      // Handle event binding from somewhere within your module
      document.addEventListener('click', module.doSomething, false);
    },
    
    doSomething: function () {
      console.log('Doing something.');
    }
  };

})();

// Initialize your module
aThing.init();

关于javascript - JS 对象字面量,this 上下文发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27801661/

相关文章:

C# 多类事件

javascript - 使用jquery animate实现滑动效果

javascript - 我如何在 Jest 中模拟这个方法链?

javascript - 在多个字段中进行 Twitter Bootstrap 的 typead 搜索

javascript - 使用悬停功能,Jquery 在随机位置生成 div

function - 在不同区间绘制多个函数 (Mathematica)

C# 事件处理方法

javascript - 在javascript中显示触发鼠标事件的元素名称

c# - 我正在从 javascript 调用 ASMX Web 服务,它可以防止我的 session 超时

javascript - 我们可以将两个函数作为参数传递给另一个函数吗?