从对象内部的函数获取范围外的变量 - Javascript

问题描述 投票:0回答:2

我在一个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();

javascript function class scope scoping
2个回答
1
投票

使用箭头函数,它将绑定到定义它的对象中的原始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();

1
投票

这样的事可能吗?

<script>
class someClass {
  constructor() {
    let that = this;
    this.foo = "bar";

    this.print = {
     variable: function() {
        console.log(that.foo);
       }    
    };

  }
}

//And I call it from the global scope

var someObject = new someClass();

someObject.print.variable();
</script>
© www.soinside.com 2019 - 2024. All rights reserved.