我有以下javascript函数:
var headerFunctionality = function () {
var isInitialised = false;
//other variables
function init() {
if (!this.isInitialised) {
//do stuff here
this.isInitialised = true;
}
};
function destroy() {
if (this.isInitialised) {
//do stuff here
this.isInitialised = false;
}
};
}
如何更改此设置以便我可以调用
headerFunctionality.init();
headerFunctionality.destroy();
我尝试添加退货,如下所示:
return {
init: init,
destroy: destroy
}
但这只允许我调用headerFunctionality()
,然后似乎触发了两个内部函数。
我所看到的一切都告诉我,我需要做这样的事情:
function headerFunctionality() {
...same inner as above
}
var header = headerFunctionality();
header.init();
这是唯一的方法还是我能够更改上述内容,以便函数是变量本身?
此目的的最佳和最常见的方法之一是使用模块模式。将function
包裹在 IIFE 中。
var headerFunctionality = (function () {
var isInitialised = false;
//other variables
function init() {
if (!isInitialised) {
//do stuff here
isInitialized = true;
}
};
function destroy() {
if (isInitialised) {
//do stuff here
isInitialised = false;
}
};
return {
init: init,
destroy: destroy
}
})();
您可以立即执行该函数:
var headerFunctionality = (function () {
var isInitialised = false; // I'm leaving it in, but it's not used anywhere! You change this.isInitiaized later which isn't the variable declared here.
//other variables
function init() {
if (!this.isInitialised) {
//do stuff here
this.isInitialised = true;
}
};
function destroy() {
if (this.isInitialised) {
//do stuff here
this.isInitialised = false;
}
};
return {
init: init,
destroy: destroy
}
}());
您也可以更改局部isInitialized
变量,而不是this.isInitialized
:
var headerFunctionality = (function () {
var isInitialised = false;
//other variables
function init() {
if (!isInitialised) {
//do stuff here
console.log( 'initialized' );
isInitialised = true;
}
};
function destroy() {
if (isInitialised) {
//do stuff here
console.log( 'destroyed' );
isInitialised = false;
}
};
return {
init: init,
destroy: destroy
}
}());
第二个示例和第一个示例之间的区别在于,在第一个(使用 this
)中,isInitialized
属性是公开的,sou 您可以从外部检查headerFunctionality.isInitialized
。在第二个示例中,保留在闭包中的局部变量被修改,并且无法从外部范围访问。
如果你想做一些"类"的事情,你可以通过这样的事情来实现你的目标:
var HeaderFunctionality = function () {
this.isInitialised = false;
//other variables (with this)
}
HeaderFunctionality.prototype.init = function() {
if (!this.isInitialised) {
//do stuff here
this.isInitialised = true;
}
};
HeaderFunctionality.prototype.destroy = function() {
if (this.isInitialised) {
//do stuff here
this.isInitialised = false;
}
};
然后,您可以创建和使用标头功能对象,如下所示:
var hf = new HeaderFunctionality();
hf.init();
console.log(hf.isInitialized); // => true
hf.destroy();
console.log(hf.isInitialized); // => false