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

NEB*_*NEB 1 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
Run Code Online (Sandbox Code Playgroud)

是否有可能使用bindg.f这样fun.g.f()会给结果in f : 100

T.J*_*der 6

是否可以在这里使用'bind'来访问'Fun'的'this'

不,因为this在你创建第二个时没有绑定f.你必须这样做Fun:

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

或者没有绑定:

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

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

如果你想f从原型中制作出使用的主体,那也是可能的:g按照你所示的方式放置原型,然后:

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

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