Accesing `this` Value When The Prototype Contains An Object?
I have a class like this: function Foo() { this._current = -1; } Foo.prototype.history = {}; Foo.prototype.history.back = function () { if (this._current === undefined) {
Solution 1:
The fundamental problem in your code is that you have only one history
object shared between all instances of Foo
. You must make it one history
per instance. A solution would be this:
functionFooHistory(foo){
this._foo = foo;
}
FooHistory.prototype.back = function() {
if (this._foo._current === undefined) {
returnalert("this._foo._current is undefined");
}
this._foo._current--;
};
functionFoo() {
this._current = -1;
this.history = newFooHistory(this);
}
var f = newFoo();
f.history.back();
(you probably want to have _current
in the FooHistory
instance instead of the Foo
instance, I tried to change as little code as possible)
Note that other solutions are possible, depending on the larger view. If you don't have any state to store in the history object then you could also have Foo.prototype.history()
return an object with a property linking back to the Foo
instance. Then you would call f.history().back()
.
Post a Comment for "Accesing `this` Value When The Prototype Contains An Object?"