如何在JS中引用当前对象的属性

时间:2012-12-25 22:36:27

标签: javascript object

  

可能重复:
  Self-references in object literal declarations

我在JS中有一些简单的对象,例如:

var object = {
 firstname : 'john',
 lastname : 'paul',
 wholename : firstname + lastname
}

这个简单的事情是行不通的; john和paul在wholename中是未定义的,所以我尝试使用'this'运算符,只有在我执行函数(getWholeName(){return this.firstname+this.lastname} )时它才有效。 但是如果我想使用变量而不是函数,我该怎么办?我也试过了object.firstname + object.lastname,但它不起作用。

2 个答案:

答案 0 :(得分:12)

无法引用该对象,但您可以动态添加属性:

var object = { 
    firstname : 'john', 
    lastname : 'paul'
};

object.wholename = object.firstname + object.lastname;

修改

为什么不将它包装在函数中?

var makePerson = function (firstname, lastname) {
    return {
        firstname: firstname,
        lastname: lastname,
        wholename: firstname + lastname  // refers to the parameters
    };
};

var object = makePerson('john', 'paul');

答案 1 :(得分:2)

在Javascript中,每个函数都是一个对象。您应该将Object的构造函数声明为如下函数:

function person(firstname,lastname)
{
this.firstname=firstname;
this.lastname=lastname;

this.wholeName=wholeName;

 //this will work but is not recommended.
 function wholeName()
 {
 return this.firstname+this.lastname;
 }
}

您可以通过原型设计为对象添加额外的方法,这是推荐的做事方式。更多信息:

http://www.javascriptkit.com/javatutors/proto.shtml