创建对象时的引用属性

时间:2014-08-01 04:04:21

标签: javascript object

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

var object = {

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

}

4 个答案:

答案 0 :(得分:0)

您可以将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} 

答案 1 :(得分:0)

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

喜欢吼叫: -

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做什么它将对象属性绑定到将在查找该属性时调用的函数。

答案 2 :(得分:0)

这可能会有所帮助

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

答案 3 :(得分:0)

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

var object = (function() {

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

  return {
    prop1: prop1,
    prop2: prop2
  };

}.bind(this);
相关问题