0
我的工作,涉及到繼承和原型鏈我的第一個項目的JS,我搞不清楚爲什麼用具體的數據一個對象的創建已經影響到數據的地方我的第二個對象。 目標是在「父對象」對象文字中有一組基本默認值,並在「子對象」對象中具有一些更具體的默認值。 子對象specificRequest接受一個數組參數用於其構造函數,把它們加到其default_params,然後調用它的原型的setOptions函數添加那些到full_params。原型鏈 - 一個對象上的設置鍵會影響同級對象?
問題是,當我創建一個specificRequest對象並初始化它時,它工作正常,但是當我創建第二個specificRequest對象時,full_params已經與第一個對象的 相同。
這可能是一些從原型是如何工作的誤解很簡單...
/////// PARENT OBJECT
function baseRequest(custom_params) {
var key;
this.full_params = {
"SignatureVersion": "2",
"Timestamp": Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'")
};
this.custom_params = custom_params;
}
baseRequest.prototype.setOptions = function(arg_options) {
var key;
if (typeof arg_options === "object") this.custom_params = arg_options;
// If an object of request options is passed, use that. Otherwise use whatever is already in the custom_params object.
for (key in this.custom_params) {
this.full_params[key] = this.custom_params[key];
}
}
///////// CHILD OBJECT
function specificRequest(mySKUList) {
var i;
this.mySKUList = mySKUList;
this.default_params = {
"Action": "myAction",
"Version": "2011-10-01"
};
for (i = 0; i < this.mySKUList.length; i++) {
var temp_sku = this.mySKUList[i];
var temp_sku_name = "SellerSKUList.SellerSKU." + (i + 1);
this.default_params[temp_sku_name] = temp_sku;
}
this.setOptions(this.default_params);
}
specificRequest.prototype = new baseRequest
///// Function to run
function testfoo() {
var skulist1 = ["AR6100", "AR6102", "WB1234"]
var skulist2 = ["XY9999"]
var req1 = new specificRequest(skulist1);
var req2 = new specificRequest(skulist2);
// Req1 has AR6100, AR6102, and WB1234 as parameters, as expected
// Req2 should only have XY9999, but instead has XY9999, AR6102, and WB1234
}
嗯,這工作。我刪除了我的一行,並把你的兩行,結果是我想要的。但我不明白你的代碼在做什麼。自從昨天以來,我一直在閱讀原型設計教程,並且我不認爲我遇到過.create()或.call()一次......所以現在我只是感到困惑。 :) – Nelluk
@ user1281743嘗試找到一個教程,其中'Object.create'使用像這樣... JavaScript教程是臭名昭着的糟糕(如PHP)。更多閱讀http://www.bennadel.com/blog/2184-Object-create-Improves-Constructor-Based-Inheritance-In-Javascript-It-Doesn-t-Replace-It.htm – Esailija