AirBnb Javascript Style Guide建议模块使用以下代码模式:
// fancyInput/fancyInput.js
!function(global) {
'use strict';
var previousFancyInput = global.FancyInput;
function FancyInput(options) {
this.options = options || {};
}
FancyInput.noConflict = function noConflict() {
global.FancyInput = previousFancyInput;
return FancyInput;
};
global.FancyInput = FancyInput;
}(this);
但是一旦你运行例如:
FancyInput({a: 1, b: 2});
控制台显示此错误“Uncaught TypeError:无法设置未定义的属性“选项””。
我试图理解为什么 FancyInput 函数内部的 this 是 Window。到目前为止,我从一开始就可以扩展这个模块模式。我应该用其他方式绑定(bind)它吗?
最佳答案
其要点是,在浏览器的全局范围内,this
是window
。在其他环境(主要是 Node.js)中,它不是 window
,而是一个不同的全局对象,但在很多方面我们关心它的行为是相同的。
您的代码不起作用,因为您需要使用 new
关键字实例化结构:
new FancyInput({a: 1, b: 2});
它创建一个新对象,以便 this.
在类方法和构造函数中工作。
关于javascript - 函数(全局){...}(这个)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989273/