简体   繁体   English

访问类方法中的对象属性

[英]Access object property in class method

In many other questions it's explained why this in the Say method below isn't always referring to an object of Foo. 在其他许多问题,它解释了为什么this在下面说的方法并不总是指美孚的对象。

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

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

I want to make sure that Say() will result in the same alert regardless of how it's called. 我想确保无论如何调用, Say()都会导致相同的警报。 I only control the code above, not the examples below. 我只控制上面的代码,而不控制下面的示例。

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

I have a roughly idea of how to build an implementation using functions. 我大致了解如何使用函数构建实现。

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

Can this be assured using the class syntax? 使用类语法可以保证吗?

Try this: 尝试这个:

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

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

With this, you force that the context of the Say method will always be this . 这样,您就可以强制Say方法的上下文始终是this

You are actually adding a new property to each Foo instance with the same name as the property Say in its prototype, so this new property will take precedence over the prototype, and setting it as the same function but with the context forced with bind. 实际上,您正在向每个Foo实例添加一个与该原型中的属性“ Say ”同名的新属性,因此该新属性将优先于该原型,并将其设置为相同的函数,但上下文使用bind强制。

EDIT: You can automate it with something like this: 编辑:您可以使用类似这样的东西使其自动化:

 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"}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM