【问题标题】:Get variable outside scope from a function inside an object - Javascript从对象内的函数获取范围外的变量 - Javascript
【发布时间】:2018-03-03 00:11:55
【问题描述】:

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

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

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


【解决方案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();

【讨论】:

    【解决方案2】:

    可能是这样的吗?

    <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>

    【讨论】:

    • 是的!我不知道我可以在 let 中引用该对象,谢谢!
    • 抱歉,它有效,但 Barmar 的回答更简洁。如果我有特权放弃投票,我会给你一个。
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2017-09-30
    • 2012-10-14
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    相关资源
    最近更新 更多