簡體   English   中英

使用`this`的JS對象給出了不確定的結果

[英]JS object using `this` gives an undefined result

好的,這是一個非常簡單的JS對象。 字符串是三個屬性,第四個是函數。

var myStringBuilder = {
  protocol: "http://",
  host: "www.mysite.com",
  fullPath: this.protocol + this.host + "/just/for/fun/",
  getFullString: function() {
    return this.fullPath;
  }
}

console.log(myStringBuilder.getFullString());  // Returns "NaN/just/for/fun"

fullPaththis.protocolthis.host均未定義。 為什么會這樣?

jsfiddle

內部JavaScript對象是基於哈希算法構造的。 因此,它們的鍵可能不會按照我們定義它們的順序在邏輯上出現。 在這種情況下,將首先定義fullPath ,並且在分配值時,取決於尚未定義它們的partOnepartTwo 這就是為什么在定義fullPath undefined它們的fullPath

如果您必須像這樣構造一個對象,我會推薦一個像這樣的構造函數

function MyStringBuilder() {
    this.protocol = "http://";
    this.host = "www.mysite.com";
    this.fullPath = this.protocol + this.host + "/just/for/fun/";
}

MyStringBuilder.prototype.getFullString = function() {
    return this.fullPath;
}

myStringBuilder();

此方法的優點是,您可以動態自定義對象的創建。 例如,您可以像這樣傳遞protocolhost

function MyStringBuilder(protocol, host) {
    this.protocol = protocol || "http://";
    this.host     = host     || "www.mysite.com";
    this.fullPath = this.protocol + this.host + "/just/for/fun/";
}

通過此更改,您應該能夠在運行時確定protocolhost

要解決部分哈希值未定義的問題,可以使用函數代替計算所得的值。 這將延遲評估。

var myStringBuilder = {
  partOne: "http://",
  partTwo: "www.mysite.com",
  fullPath: function(){ return this.partOne + this.partTwo + "/just/for/fun/" }
}

如果我在以前的答案的所有有價值的信息,同意回答對問題的精確點,該fullPath屬性定義不正確,因為它不是在一個函數上下文初始化,所以this並不是指對象myStringBuilder。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM