【发布时间】:2012-11-25 22:02:43
【问题描述】:
我想创建一个带有一些隐藏(使用闭包)变量的对象,以及利用这些隐藏变量的方法。但是,我不想为每个实例重新创建这些方法。我想让他们记住一次。我正在使用普通函数来实例化对象。
这里有一些代码:
function Mario () {
var mario = {}; // create the obj
mario.name = "Mario"; // create a property on it
mario.hp = (function () { // set up a closure
var currentHp = Mario.baseHp * 100; // create a "hidden" variable
return function (value) { // return the hp function that utilizes the hidden currentHp variable
if (!!value) {
return currentHp = ((currentHp * Mario.baseHp) + value);
}
return currentHp * Mario.baseHp;
};
}());
return mario; // send along the newly created object
}
Mario.baseHp = 1;
var mario = Mario();
log(mario);
log(mario.hp());
log(mario.hp(-20));
log(mario.hp());
这里的问题是,每次我创建另一个“mario”对象时,我都会在内存中再次创建 hp 函数。到目前为止,这是我对解决方案的尝试:
function Mario () {
var mario = {}; // create the obj
mario.name = "Mario"; // create a property on it
mario.hp = (function () { // set up a closure
var currentHp = Mario.baseHp * 100; // create a "hidden" variable
return Mario.hp; // reference the hp function below..... but the context is wrong, it needs access to currentHp variable.
}());
return mario; // send along the newly created object.
}
Mario.baseHp = 1;
Mario.hp = function (value) { // Create the hp function once in memory
if (!!value) {
return currentHp = ((currentHp * Mario.baseHp) + value);
}
return currentHp * Mario.baseHp;
};
var mario = Mario();
log(mario);
log(mario.hp());
log(mario.hp(-20));
log(mario.hp());
但显然 Mario.hp 的上下文是错误的。我在想可能有一种方法可以使用 call 或 apply 来解决这个问题。任何帮助都会动摇!
【问题讨论】:
-
我不确定你想做什么,但you may find this interesting.
-
哇,这太令人费解了。你能想出一个minimalist的例子来说明这个问题吗?
-
@Pointy 谢谢!我以前遇到过 bind,但现在对我来说更有意义了。
标签: javascript oop closures