var A = {
options: {
attr1: 100,
attr2: 300,
attr3: attr1 * attr2 // ReferenceError: attr1 is not defined
}
};
對象字面量定義階段不創建作用域:
attr1、attr2 是屬性鍵值,而非變量,無法在同一字面量內直接引用。
var A = {
options: {
attr1: 100,
attr2: 300,
getAttr3: function() { return this.attr1 * this.attr2; }
}
};
console.log(A.options.getAttr3()); // 30000
var A = { options: {} };
A.options.attr1 = 100;
A.options.attr2 = 300;
A.options.attr3 = A.options.attr1 * A.options.attr2;
function createOptions(a1, a2) {
return {
attr1: a1,
attr2: a2,
get attr3() { return this.attr1 * this.attr2; } // ES5 getter
};
}
var A = { options: createOptions(100, 300) };
class Options {
constructor(attr1, attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
get attr3() { return this.attr1 * this.attr2; }
}
const A = { options: new Options(100, 300) };
對象字面量是「靜態數據結構」,動態計算屬於「行為」,應通過方法/getter 封裝。這也是「數據與行為封裝」面向對象原則的體現。