我想从类中调用其他类方法但是当某个方法调用方法时,我将失去对this
的访问权限,因为现在this
是调用方法而不能使用其他类方法或获取数据成员。
例如:
class someclass{
_this = this;
foo(){
this.bar();
}
bar(){
this.baz(); // this is foo not someclass
_this.baz(); // _this is not defined
}
baz(){
}
}
那么如何才能始终访问实际的类以便能够调用其方法并从其方法中使用其数据成员呢?
编辑:在我的实际代码中,我有另一个使用事件调用foo
的对象,因此在输入this
而不是foo
时,someclass
就是该对象。< / p>
答案 0 :(得分:5)
javascript中的类方法不受约束。含义
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(){
}
}
)
// 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()
console
"from bar"
"from foo "
lib/my_engine/engine.rb
答案 1 :(得分:0)
class someClass2 {
bar() {
console.log('bar from someClass2')
}
}
class someClass {
constructor() {
//instantiate an object of someClass2 to access all itsmethod
this.obj2 = new someClass2()
}
foo () {
console.log('foo from someClass')
}
barFromObj2(){
return this.obj2.bar()
}
}
var obj = new someClass();
obj.foo(); // return foo from someClass
// access the bar method from the someClass2
obj.barFromObj2(); // return bar from someClass2
&#13;