function(global){...}(this) 是如何工作的?
how function(global){...}(this) works?
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: Cannot set property 'options' of undefined"。
我试图理解为什么 FancyInput 函数内部是 Window。到目前为止,我从一开始就可以扩展这个模块模式。我应该以其他方式绑定它吗?
它的要点是 this
在全局范围内,在浏览器中,是 window
。在其他环境中(主要是node.js),它不是window
,而是一个不同的全局对象,但在很多方面我们关心它的行为是一样的。
您的代码无法运行,因为您需要使用 new
关键字实例化结构:
new FancyInput({a: 1, b: 2});
创建一个新对象,以便 this.
在 class 方法和构造函数中工作。
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: Cannot set property 'options' of undefined"。
我试图理解为什么 FancyInput 函数内部是 Window。到目前为止,我从一开始就可以扩展这个模块模式。我应该以其他方式绑定它吗?
它的要点是 this
在全局范围内,在浏览器中,是 window
。在其他环境中(主要是node.js),它不是window
,而是一个不同的全局对象,但在很多方面我们关心它的行为是一样的。
您的代码无法运行,因为您需要使用 new
关键字实例化结构:
new FancyInput({a: 1, b: 2});
创建一个新对象,以便 this.
在 class 方法和构造函数中工作。