Accesing `this` value when the prototype contains an object?

后端 未结 1 1002
情话喂你
情话喂你 2021-01-23 06:42

I have a class like this:

 function Foo() {
   this._current = -1;
 }
 Foo.prototype.history = {};
 Foo.prototype.history.back = function () {
   if (th         


        
1条回答
  •  Happy的楠姐
    2021-01-23 07:34

    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:

    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();

    (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().

    0 讨论(0)
提交回复
热议问题