Javascript 类别-';这';vs';自我';
我正在使用新的,很难理解为什么我可以引用Javascript 类别-';这';vs';自我';,javascript,es6-class,Javascript,Es6 Class,我正在使用新的,很难理解为什么我可以引用这个变量是其中一种方法 //阶级 class Form{ constructor(){ var self = this; } assemble(){ log(self); } } //叫 var form = new Form(); form.assemble(); //返回 window object (not the reference to the class object
这个
变量是其中一种方法
//阶级
class Form{
constructor(){
var self = this;
}
assemble(){
log(self);
}
}
//叫
var form = new Form();
form.assemble();
//返回
window object (not the reference to the class object)
此
不是变量。它更像是函数的隐藏参数
在您的示例中,您无法访问self
,因为它是构造函数中的局部变量,因此它对assemble
方法不可用
您根本不需要self
作为示例,只需使用this
:
class Form {
assemble(){
log(this); // ***
}
}
var form = new Form();
form.assemble();
class Form {
constructor(){
var self = this;
this.assemble = () => {
log(this);
};
}
}
var form = new Form();
form.assemble(); // Works
var f = form.assemble;
f(); // Also works
如果您将form.assemble
传递给某个不能保证使用正确的this
调用它的对象,您可以通过在构造函数中定义它来将assemble
定义为实例函数成员;然后它将关闭self
。但在ES2015及以上版本中,您不需要self
;只需使用箭头功能,它将关闭此:
class Form {
assemble(){
log(this); // ***
}
}
var form = new Form();
form.assemble();
class Form {
constructor(){
var self = this;
this.assemble = () => {
log(this);
};
}
}
var form = new Form();
form.assemble(); // Works
var f = form.assemble;
f(); // Also works
但很有可能您不需要这样做。可能重复的可能重复:self是窗口上实际存在的属性:您正在构造函数中将它重新定义为局部变量,然后暂时不使用它。在Assembly()方法中,您实际上并没有引用在构造函数中声明的自变量,而是引用window.self.Thank!这么简单,只是不习惯我的老方法,哈哈。在构造函数中定义函数比将其定义为普通类函数并在构造函数中绑定(即
this.foo=this.foo.bind(this)
)有什么优势吗?我个人认为后者更具可读性。@Timo:如果你像我上面所做的那样使用箭头功能,不,这两种方式都没有技术优势,只是风格不同而已。我的意思是,好吧,从技术上讲,bind
解决方案有一个额外的函数(只有一个,不是每个实例一个),但谁在乎呢?如果在构造函数中使用函数
函数而不是箭头(但为什么?:-),那么绑定
解决方案会更好,因为在这种情况下,您可以使用超级
,但不能使用构造函数中创建的函数。@t.J.Crowder感谢您的澄清!