[英]Access object property in class method
在其他许多问题,它解释了为什么this
在下面说的方法并不总是指美孚的对象。
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
”同名的新属性,因此该新属性将优先于该原型,并将其设置为相同的函数,但上下文使用bind强制。
编辑:您可以使用类似这样的东西使其自动化:
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.