【问题标题】:Reference property when creating object [duplicate]创建对象时的引用属性[重复]
【发布时间】:2014-09-24 05:06:23
【问题描述】:

在创建对象本身时如何引用对象的属性?下面的例子不起作用:

var object = {

  prop1 : $(this).find('.foo');
  prop2 : this.prop1.find('.bar');

}

【问题讨论】:

标签: javascript object


【解决方案1】:

我假设您有兴趣避免重新计算 $(this).find('.foo'),在这种情况下您可以执行以下操作:

var object = (function() {

  var prop1 = $(this).find('.foo'),
      prop2 = prop1.find('bar');

  return {
    prop1: prop1,
    prop2: prop2
  };

}.bind(this);

【讨论】:

    【解决方案2】:

    这可能会有所帮助

     var obj = {
     prop1 : $(this).find('.foo');
     prop2 : function() { return this.prop2.find('.bar'); }
    };
    

    【讨论】:

      【解决方案3】:

      您不能引用尚未创建的对象的属性。您可以拥有一个将在创建对象后调用的函数。那么您可以使用this 引用property

      如下:-

      obj = {
         a1:3,
         a2:function(){return this.a1}
      };
      

      所以调用obj.a2() 将在此处返回3

      或者如果你不想打电话,比如function,请使用Get

      obj = {
         a1:3,
         get a2(){return this.a1}
      };
      
      obj.a2; //returns 3
      

      get 的基本作用它将对象属性绑定到将在查找该属性时调用的函数。

      【讨论】:

        【解决方案4】:

        您可以将 new 关键字与匿名函数一起使用:

        var $self = $(this);
        
        var object = new function () {
        
          this.prop1 = $self.find('.foo');
          this.prop2 = this.prop1.find('.bar');
        
        };
        

        从技术上讲,该对象将具有与对象字面量不同的 constructor 属性,但这不太可能对大多数用例造成问题。

        作为一个简单的演示:

        var obj = new function () {
          this.x = 7;
          this.y = this.x * 2;
        };
        
        console.log(obj); // Object {x: 7, y: 14} 
        

        【讨论】:

        • 这对我有用 - 谢谢
        • @Chris 不客气
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-01
        • 2012-03-13
        • 2012-06-10
        • 1970-01-01
        • 2011-03-10
        • 2017-03-06
        相关资源
        最近更新 更多