[英]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"
在fullPath
, this.protocol
和this.host
均未定義。 為什么會這樣?
內部JavaScript對象是基於哈希算法構造的。 因此,它們的鍵可能不會按照我們定義它們的順序在邏輯上出現。 在這種情況下,將首先定義fullPath
,並且在分配值時,取決於尚未定義它們的partOne
和partTwo
。 這就是為什么在定義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();
此方法的優點是,您可以動態自定義對象的創建。 例如,您可以像這樣傳遞protocol
或host
值
function MyStringBuilder(protocol, host) {
this.protocol = protocol || "http://";
this.host = host || "www.mysite.com";
this.fullPath = this.protocol + this.host + "/just/for/fun/";
}
通過此更改,您應該能夠在運行時確定protocol
和host
。
要解決部分哈希值未定義的問題,可以使用函數代替計算所得的值。 這將延遲評估。
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.