从对象内的函数获取作用域外的变量 - Javascript

Blu*_*eph 2 javascript scope class function scoping

我在类内的对象内有一个函数。

类的对象已初始化,我想调用该函数,但该函数需要在类的构造函数上定义一个变量。

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();
Run Code Online (Sandbox Code Playgroud)

它将打印

不明确的

我知道这是一个不同的范围,也许我无法访问它。

这样做的目的是让我的功能有一定的顺序。

我想访问我的函数,例如 someObject.print.variable();

Bar*_*mar 5

使用箭头函数,它将绑定到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();
Run Code Online (Sandbox Code Playgroud)