[英]Javascript object literal notation, using functions
我正在使用文字符號創建一個對象。 是否有可能讓某些屬性使用先前定義的屬性作為其值?
例如:
var test = {
prop1: obj1,
prop2: obj2,
prop3: (prop1!=null)?prop1:prop2
};
如果您嘗試執行var x = { 'a': 1, 'b': xa }
那么它將無效。 由於x
未完成定義。
但你可以做點什么
var
a = 12,
b = 24,
c = a + b; // 36
這是因為每個var定義都是按順序解釋的。 基本相當於
var a = 12;
var b = 24;
var c = a + b;
但是對於對象和數組,整個定義被解釋一次。
不,是的。
以下是不可能的:
var o = {
a : 42,
b : o.a //raises a TypeError, o is not defined
};
var o = {
a : b : 42 //raises a SyntaxError, unexpected :
};
但是,以下是:
//referencing a pre-existing variable is obviously possible
var ans = 42;
var o = {
a : ans,
b : ans
};
var o = {
a : 42
};
//after the variable has been declared, you can access it as usual
o.b = o.a;
如果您覺得值是單個語句的限制,您可以始終使用匿名函數:
var o = {
a : (function () {
doStuff();
return otherStuff();
}())
};
保持你的榜樣:
var test = {
prop1: obj1,
prop2: obj2,
prop3: (function () {
return (test.prop1!=null)?test.prop1:test.prop2;
})()
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.