javascript - 在原型(prototype)中保留 'this' 上下文

标签 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

是否可以在 g.f 中使用 bind 使得 fun.g.f() 将在 f 中给出结果 :100 ?

最佳答案

Is it possible to use 'bind' here to access 'this' of 'Fun'

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

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

或者没有绑定(bind):

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

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

如果您想从原型(prototype)中使用 f 的主体,这也是可能的:如您所示,将 g 放在原型(prototype)上,然后:

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 被替换为对新对象的引用,它就会崩溃。

关于javascript - 在原型(prototype)中保留 'this' 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626114/

相关文章:

javascript - 将元素粘贴到浏览器窗口/容器的底部

javascript - 为什么对象的构造函数返回 Object() 而不是它的构造函数?

javascript - 针对某个类的最近标签,而不是原型(prototype)中的第一个标签

JavaScript函数调用/应用字符串

javascript - "this"在构造函数中分配的函数中如何工作?

javascript - 如何在 NextJS+React 中使用 api 生成的内容创建用户可自定义的动态 url?

javascript - 单击按钮清除输入字段

Jquery 选择器——this vs id vs class

javascript - 导致错误的全局变量

javascript 专有日期格式和原型(prototype)