Ion*_*zău 1 javascript prototype object
我有一个这样的课:
function Foo() {
this._current = -1;
}
Foo.prototype.history = {};
Foo.prototype.history.back = function () {
if (this._current === undefined) {
return alert("this._current is undefined");
}
--this._current; // `this` is the history object
};
Run Code Online (Sandbox Code Playgroud)
如何Foo在back方法中访问实例?
我解决的问题是做这样的事情:
var f = new Foo();
f.history.back = f.history.back.bind(f);
Run Code Online (Sandbox Code Playgroud)
有更好的解决方案吗?对每个Foo实例都这样做对我来说听起来不太好.
这是一个例子:
function Foo() {
this._current = -1;
}
Foo.prototype.history = {};
Foo.prototype.history.back = function() {
if (this._current === undefined) {
return alert("this._current is undefined");
}
--this._current; // `this` is the history object
};
var f = new Foo();
f.history.back();Run Code Online (Sandbox Code Playgroud)
我知道它应该如此,但解决这类问题的正确方法是什么?
代码中的基本问题是,history在所有实例之间只共享一个对象Foo.您必须为history每个实例创建一个.解决方案是:
function FooHistory(foo){
this._foo = foo;
}
FooHistory.prototype.back = function() {
if (this._foo._current === undefined) {
return alert("this._foo._current is undefined");
}
this._foo._current--;
};
function Foo() {
this._current = -1;
this.history = new FooHistory(this);
}
var f = new Foo();
f.history.back();Run Code Online (Sandbox Code Playgroud)
(您可能希望_current在FooHistory实例中而不是Foo实例中,我尝试尽可能少地更改代码)
请注意,其他解决方案是可能的,具体取决于更大的视图.如果您没有任何状态存储在历史记录对象中,那么您还可以Foo.prototype.history()返回一个具有链接回Foo实例的属性的对象.然后你会打电话f.history().back().