简体   繁体   English

browserify模块中的“ this”上下文

[英]'this' context in browserify modules

In a simple browserify app, I'd like to use the this keyword to reference other functions in an exported object, but it doesn't seem to be working as I'd expect it to: 在一个简单的browserify应用程序中,我想使用this关键字来引用导出对象中的其他功能,但是它似乎并没有按照我的预期工作:

(function() {
  module.exports = {
    a: function() {
      console.log('Hello World');
    },
    b: function() {
      this.a(); // Problem: this is set to window.document
    }
  };
})();

I'd assumed that the above code would work, but it seems that this is set to window.document instead of the exported object. 我以为上面的代码可以工作,但是似乎将this设置为window.document而不是导出的对象。 I'm fairly sure I've had this working in the past, so it's probably something simple, but I'm a bit stuck on it! 我相当确定我过去曾经做过这项工作,所以这可能很简单,但是我对此有些犹豫!

I'm aware that I could export the object itself to window , or else make it a named variable that can be referenced, but I'd like to understand why the above code doesn't work. 我知道我可以将对象本身导出到window ,或者将其设置为可以引用的命名变量,但是我想了解为什么上面的代码不起作用。

Many thanks! 非常感谢!

要将“ this”设置为对象,您需要将此函数作为对象属性来调用,例如foo.a()或使用call / apply显式设置“ this” bar.a.apply(foo,[args])

You are almost there. 你快到了 Change your code to below and it works. 将您的代码更改为下面的代码即可。

(function () {
   var module = new Object();
   module.exports = {
        a : function () {
            console.log('Hello World');
        },
        b : function () {
            this.a();
        }
   };
   module.exports.b();
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM