我在类内的对象内有一个函数。
该类的对象已初始化,我想调用该函数,但该函数需要在Class的构造函数上定义的变量。
class someClass {
constructor() {
this.foo = "bar";
this.print = {
variable: function() {
console.log(this.foo);
}
};
}
}
// And I call it from the global scope
var someObject = new someClass();
someObject.print.variable();
它将打印
未定义
我知道这是一个不同的范围,也许我无法使用它。
目的是使我的功能有一定的顺序。
我想访问我的函数,如someObject.print.variable();。
使用箭头函数,它将绑定到this
定义它的对象中的原始对象。
class someClass {
constructor() {
this.foo = "bar";
this.print = {
variable: () => {
console.log(this.foo);
}
};
}
}
// And I call it from the global scope
var someObject = new someClass();
someObject.print.variable();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句