【问题标题】:How to change scope of JavaScript getter?如何更改 JavaScript getter 的范围?
【发布时间】:2016-08-25 16:45:17
【问题描述】:

给定以下对象:

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return this.fname + ' ' + this.lname
        }
    }
};

尝试访问myObj.values.fullName 时,会返回undefined undefined,因为this 的上下文设置为myObj.values,而不是myObj

有办法改变吗?我尝试了所有我能想到的bind 组合,但大多数情况下这只会导致语法错误,因为fullName 不是常规函数。

【问题讨论】:

  • 你不能像return myObj.fname + ' ' + myObj.lname一样使用它吗?

标签: javascript scope this getter


【解决方案1】:

您只能通过myObj.fnamemyObj.lname 访问父对象属性。

var myObj = {
    fname: 'John',
    lname: 'Doe',
    values: {
        get fullName() {
            return myObj.fname + ' ' + myObj.lname
        }
    }
};

【讨论】:

    【解决方案2】:

    You cannot access parent objects in Javascript。您需要将 getter 嵌套在 values 元素中吗?以下内容可以正常工作:

    var myObj = {
        fname: 'John',
        lname: 'Doe',
        get fullName() {
            return this.fname + ' ' + this.lname
        }
    };
    
    alert(myObj.fullName)
    

    【讨论】:

      【解决方案3】:

      将“this”替换为对象的名称

      选项 1:

      var myObj = {
          fname: 'John',
          lname: 'Doe',
          values: {
              get fullName() {
                  return myObj.fname + ' ' + myObj.lname
              }
          }
      };
      

      另一种选择:

      选项 2:

      var myObj = {
          fname: 'John',
          lname: 'Doe',
          values: {
              get fullName() {
                  return this.parent.fname + ' ' + this.parent.lname
              }
          },
          init: function(){
              this.values.parent = this;
              delete this.init; 
              return this;
          }
      }.init()
      

      【讨论】:

      • 如果myObj 对象有多个实例,这会起作用吗?
      • 这是一个好点。它适用于第二个选项(在原始帖子中编辑)
      • @evolutionxbox,我的回答会让你满意吗?
      • 我想是的。它与显示模块模式非常相似。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2018-12-06
      • 2015-09-14
      • 2019-04-13
      • 2017-08-02
      • 1970-01-01
      相关资源
      最近更新 更多