在原型中保留'this'上下文

时间:2015-09-17 08:48:39

标签: javascript prototype this

这个问题已经被提出,建议的解决方案是使用'bind'。但是如何在这种情况下使用'bind'?

var Fun = function(){
    this.count = 100;
}

Fun.prototype.f = function(){
    console.log("in f : " + this.count);
}

Fun.prototype.g = {
    f : function(){
        console.log("in g-f : " + this.count);
        // Is it possible to use 'bind' here to access 'this' of 'Fun'
    }
}

fun = new Fun();
fun.f(); // Results - in f : 100
fun.g.f(); // Results - in g-f : undefined
fun.g.f.bind(fun)(); // Results - in f : 100

是否可以在bind中使用g.ffun.g.f()会给出结果in f : 100

2 个答案:

答案 0 :(得分:6)

  

是否可以使用' bind'在这里访问'这个' ' Fun'

不,因为在你创建第二个this时,没有f绑定。您必须在Fun中执行此操作:

var Fun = function(){
    this.count = 100;
    this.g = {
        f: function() {
            console.log("in g-f : " + this.count);
        }.bind(this)
    };
};

或没有绑定:

var Fun = function(){
    var t = this;
    this.count = 100;
    this.g = {
        f: function() {
            console.log("in g-f : " + t.count);
        }
    };
};

这涉及为每个实例创建一个新函数。即使创建了不同的函数对象,现代浏览器引擎也会在实例之间重用函数的代码

如果您想要使用原型中使用的f主体,那也可以:在您展示的原型上放置g,然后:< / p>

var Fun = function(){
    var t = this;
    var oldg = this.g;
    this.count = 100;
    this.g = {
        f: function() {
            return oldg.f.apply(t, arguments);
        }
    };
};

现在,如果在创建实例后Fun.prototype.g.f发生更改,则使用更新后的版本。但如果将Fun.prototype.g替换为对新对象的引用,它就会中断。

答案 1 :(得分:1)

不,因为fun.g是一个不同的对象。您所能做的就是在g的所有实例中放置一个不同的Fun对象,并在其中放置一个绑定函数f

function Fun() {
  this.count = 100;

  this.g = {
    f: function() {
      console.log("in g-f : " + this.count);
    }.bind(this);
  };
}

Fun.prototype.f = function() {
  console.log("in f : " + this.count);
};
相关问题