shi*_*zou 3 javascript syntax ecmascript-6 es6-class
我想从类中调用其他类方法但是当一些方法调用一个方法时,我失去了访问权限,this因为现在this是调用方法而不能使用其他类方法或获取数据成员.
例如:
class someclass{
_this = this;
foo(){
this.bar();
}
bar(){
this.baz(); // this is foo not someclass
_this.baz(); // _this is not defined
}
baz(){
}
}
Run Code Online (Sandbox Code Playgroud)
那么我怎么能总是访问实际的类来调用它的方法并从其方法中使用它的数据成员呢?
编辑:在我的实际代码中,我有另一个foo使用事件调用的对象,因此this在进入时foo不是someclass.
默认情况下,javascript中的类方法不受约束.意义
this值取决于它们的调用方式,而不是它们是如何定义的.
this在es6中绑定(维护)
class SomeClass{
constructor(){
// this binding maintains the value of this
// inside these methods during future calls .
this.foo = this.foo.bind(this)
this.bar = this.bar.bind(this)
this.baz = this.baz.bind(this)
}
foo(){
this.bar();
console.log('from foo')
}
bar(){
this.baz(); // this is foo not someclass
console.log('from bar')
}
baz(){
}
}
Run Code Online (Sandbox Code Playgroud)
// if you are using babel you can use arrow function/methods
class SomeClass{
foo = () => {
this.bar();
console.log('from foo ')
}
bar = ()=> {
this.baz(); // this is foo not someclass
console.log('from bar')
}
baz(){
}
}
const s = new SomeClass()
s.foo()
Run Code Online (Sandbox Code Playgroud)
console
"from bar"
"from foo "
| 归档时间: |
|
| 查看次数: |
3137 次 |
| 最近记录: |