我在类中的对象中有一个函数。
类的对象已初始化,我想调用函数,但函数需要在类的构造函数中定义一个变量。
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();
它会打印
undefined
我知道是一个不同的范围,也许我无法访问它。
这样做的目的是让我的函数有一些顺序。
我想访问我的函数,比如 someObject.print.variable();
最佳答案
使用箭头函数,它将绑定(bind)到定义它的对象中的原始 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();
关于javascript - 从对象内部的函数获取作用域外的变量 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49079277/