我有一些函数,仅在 dom 中的某些底层“内容”发生更改时才返回值,如下所示:
function getFoo() {
if (typeof this.prev === "undefined") {
this.prev = null;
}
// calculate x
if (x != this.prev) {
this.prev = x;
return this.prev;
} else {
return;
}
}
如果计算机变量 x
未更改,则 foo
不返回任何内容。当从控制台调用时,这似乎工作正常。
接下来,我将其包装在一个对象中,以便我可以顺序调用类似的函数:
function bar () {
this.plugins = {
foo: getFoo
};
for (var attr in this.plugins) {
if (this.plugins.hasOwnProperty(attr)) {
console.log(this.plugins[attr]());
}
}
奇怪的是,当我现在调用 bar()
时,底层函数(例如 getFoo
)总是返回值——即使底层的东西在dom 没有改变。似乎这些函数在使用时被销毁(在 plugin
对象中)——我如何保留这些函数?
最佳答案
好吧,当你调用 bar()
时,它会调用
this.plugin.getFoo();
因此 getFoo
中的 this
将引用 this.plugins
。
每次调用 bar()
时,都会使用新对象初始化 this.plugin
:
this.plugins = {
foo: getFoo
};
<小时/>
老实说,你的结构似乎很困惑。您知道 bar()
函数中的 this
引用了 window
对象吗?您正在用它“污染”全局 namespace 。如果直接调用 getFoo
,则同样如此。
也许你应该有更多这样的东西:
var bar = {
plugins: {foo: getFoo},
run: function() {
for (var attr in this.plugins) {
if (this.plugins.hasOwnProperty(attr)) {
console.log(this.plugins[attr]());
}
}
}
};
您可以调用:
bar.run();
<小时/>
在函数调用之间拥有持久和私有(private)数据的另一种方法是使用闭包:
var getFoo = (function() {
var prev = null;
return function(x){
if (x != prev) {
prev = x;
return prev;
}
}
}());
此处,立即函数返回的函数在 prev
上结束。无论您在何处分配 getFoo
,它始终可以访问 prev
,并且不会覆盖其他范围内的任何其他 prev
变量。
我认为将 x
传递给函数也更好。
关于javascript - 对象内 javascript 函数的持久性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5900012/