我有以下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();
这是唯一的方法,还是我能够改变上述内容,因此函数本身就是变量?
答案 0 :(得分:3)
实现这一目标的最佳和最常见的方法之一是使用module pattern。将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
}
})();
答案 1 :(得分:1)
您可以立即执行该功能:
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
属性,您可以从外部检查headerFunctionality.isInitialized
。在第二个示例中,保留在闭包中的局部变量被修改,无法从外部作用域访问。
答案 2 :(得分:0)
如果你想做某事"类似于"你可以通过以下方式实现目标:
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