如何在JS中引用当前对象的属性 [英] How to reference properties of current object in JS
问题描述
可能的重复:
对象字面量声明中的自引用
我在 JS 中有一些简单的对象,比如这个例子:
I have some simple objects in JS like this example:
var object = {
firstname : 'john',
lastname : 'paul',
wholename : firstname + lastname
}
好吧,这个简单的事情行不通;john 和 paul 在全名中未定义,因此我尝试使用this"运算符,该运算符仅在我执行函数 (getWholeName(){return this.firstname+this.lastname} )
时才有效.但是如果我想使用一个变量而不是一个函数,我该怎么办?我也试过 object.firstname + object.lastname
但它不起作用.
Well this simple thing doesn't work; john and paul are undefined in wholename, so I tried to use the 'this' operator which works ONLY if I do a function (getWholeName(){return this.firstname+this.lastname} )
.
But if I want to use a variable and not a function, how can I do? I also tried object.firstname + object.lastname
but it doesn't work.
推荐答案
没有办法引用对象,但是可以动态添加属性:
There is no way to reference the object, but you can add the properties dynamically:
var object = {
firstname : 'john',
lastname : 'paul'
};
object.wholename = object.firstname + object.lastname;
为什么不把它包装在一个函数中?
And why not wrap it in a function?
var makePerson = function (firstname, lastname) {
return {
firstname: firstname,
lastname: lastname,
wholename: firstname + lastname // refers to the parameters
};
};
var object = makePerson('john', 'paul');
这篇关于如何在JS中引用当前对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!