網站搜尋

JavaScript 物件如何引用自身的值?


假設我有以下的 JavaScript:

var obj = {
 key1 : "it ",
 key2 : key1 + " works!"
};
alert(obj.key2);

這會出現「key1 未定義」的錯誤。我已經嘗試過

this.key1
this[key1]
obj.key1
obj[key1]
this["key1"]
obj["key1"]

而且它們似乎從未被定義過。

我如何能讓 key2 參照 key1 的值?

答案#1

也許你可以考慮將屬性移到函數上。我的意思是像這樣的東西:

var obj = {
  key1: "it ",
  key2: function() {
    return this.key1 + " works!";
  }
};

alert(obj.key2());

答案#2

這可以透過使用建構函數而不是字面量來達成

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

答案#3

在初始化物件之前,你不能引用該物件的屬性;請使用外部變數。

var key1 = "it";
var obj = {
  key1 : key1,
  key2 : key1 + " works!"
};

另外,這不是一個「JSON 對象」;它是一個 Javascript 對象。JSON 是用字串表示對象的一種方法(這個字串恰好是有效的 Javascript 代碼)。

答案#4

另一種選擇是使用 getter/setter 方法。

例如,如果你只關心讀取計算出的數值:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

不過,上面的程式碼不會讓你為 key2 定義另一個值。

所以,如果你也想重新定義 key2 的值,事情就會變得有點複雜。它將永遠是計算出來的值。很可能這正是你想要的。

然而,如果你希望能夠重新定義 key2 的值,那麼你將需要一個獨立於計算之外的地方來緩存它的值。

有點像這樣:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

另一個有趣的替代方法是使用一個自我初始化的物件:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

答案#5

因為定義 obj 的語句尚未完成,key1 尚不存在。可以考慮這個解決方案:

var obj = { key1: "it" };
obj.key2 = obj.key1 + ' ' + 'works!';
// obj.key2 is now 'it works!'

答案#6

那不是 JSON 物件,那是透過物件字面值符號建立的 JavaScript 物件。(JSON 是用於資料交換的文字表示法(更多資訊)。如果你處理的是 JavaScript 原始程式碼,而不是字串,那你處理的就不是 JSON。)

在物件初始化器中無法參考正在初始化的物件的另一個鍵,因為在初始化器完成之前無法取得正在建立的物件的參考。(在這種情況下沒有類似 this 的關鍵字。)

答案#7

你也可以在函數內部使用 obj 來參考,而不是 this。

var obj = {
    key1: "it",
    key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());