创建对象时引用属性

Reference property when creating object

本文关键字:属性 引用 创建对象      更新时间:2023-09-26

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

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

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

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} 

不能引用尚未创建的对象的属性。你可以有一个函数,它将在对象创建后被调用。因此,您可以使用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的基本功能它将一个对象属性绑定到一个函数,该函数在查找该属性时将被调用

这可能会有帮助

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

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

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