在许多其他问题中,解释了为什么以下Say方法中的this并不总是引用Foo的对象。

class Foo {
    constructor(){
        this.bar = "baz";
    }

    Say(){
        alert(this.bar);
    }
}


我想确保Say()将导致相同的警报,而不管其调用方式如何。
我仅控制上面的代码,而不控制下面的示例。

var f = new Foo();
f.Say();                                    //"baz"
element.addEventListener("click", f.Say);   //undefined
f.Say.call({bar: "no"});                    //"no"


我大致了解如何使用函数构建实现。

function Foo(){
    var bar = "baz";
    return {
        Say(){
            alert(bar);
        }
    }
}


可以使用类语法确保吗?

最佳答案

尝试这个:

class Foo {
    constructor(){
        this.bar = "baz";
        this.Say = this.Say.bind(this);
    }

    Say(){
        alert(this.bar);
    }
}


这样,您可以强制Say方法的上下文始终为this

实际上,您正在向每个Foo实例添加一个与原型中的属性Say相同名称的新属性,因此,此新属性将优先于原型,并将其设置为相同的函数,但强制使用上下文与绑定。

编辑:您可以使用类似这样的东西使其自动化:



class Foo {
    constructor(){
        this.bar = "baz";
        Object.getOwnPropertyNames(this.constructor.prototype).forEach((i) => {
            if (typeof this.constructor.prototype[i] == "function" && this.constructor.prototype[i] != this.constructor) {
                this[i] = this.constructor.prototype[i].bind(this);
            }
        });
    }

    Say(){
        alert(this.bar);
    }
}
var f = new Foo();
f.Say();
f.Say.call({bar: "no"});   

关于javascript - 访问类方法中的对象属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51565566/

10-12 12:33
查看更多