[英]Why 'this.userid' is assigning undefined value? does "this" pointing to the class or the object itself? timestamp_generate_function() works though
為什么“this.userid”分配未定義的值? “這個”是指向 class 還是 object 本身? timestamp_generate_function() 雖然有效。
class price_update {
constructor(api_key, url_endpoint, user_id, store_name) {
this.api_key = api_key;
this.url_endpoint = url_endpoint;
this.userid = user_id;
this.store_name = store_name;
}
#updatePriceQuantity_parameters = {
Action: "UpdatePriceQuantity",
Format: "json",
Timestamp: this.#timestamp_generate_function(),
UserID: this.userid,
Version: "1.0"
};
“這個”是指向 class 還是 object 本身?
在這種情況下, this
是指 object。 不,不是 JavaScript 的 object ( {}
) 數據類型,而是使用new price_update()
實例化的price_update
class 的實例。
哦,對了,你有一個錯字(構造函數參數中的user_id1
而不是user_id
)。 user_id
沒有在那里定義(即使 SO mods 編輯了問題),因此未定義。
原帖截圖:
class price_update {
constructor(api_key, url_endpoint, user_id1, store_name) {
this.api_key = api_key;
this.url_endpoint = url_endpoint;
this.userid = user_id;
this.store_name = store_name;
}
#updatePriceQuantity_parameters = {
Action: "UpdatePriceQuantity",
Format: "json",
Timestamp: this.#timestamp_generate_function(),
UserID: this.userid,
Version: "1.0"
};
“這個”是指向 class 還是 object 本身? 是的。 this
指向 object 本身。
為什么“this.userid”分配未定義的值? 您試圖在定義之前基於屬性( this.userid
)設置值(在構造函數中或其他任何地方)。
相反,您將希望在構造函數中執行以下操作:
class price_update {
constructor(api_key, url_endpoint, user_id, store_name) {
this.api_key = api_key;
this.url_endpoint = url_endpoint;
this.userid = user_id;
this.store_name = store_name;
this.#updatePriceQuantity_parameters.UserID = user_id;
}
#updatePriceQuantity_parameters = {
Action: "UpdatePriceQuantity",
Format: "json",
Timestamp: this.#timestamp_generate_function(),
UserID: '',
Version: "1.0"
};
請注意,當我們在 object 本身的實例內部時,我們在構造函數中設置值。 你可以這樣做,如果你願意,也可以用其他方法。 無論哪種方式,您都必須先實例化 object,然后才能訪問/應用您在構建期間設置的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.