我正在处理我的第一个涉及继承和原型链的 JS 项目,我很困惑为什么使用特定数据创建一个对象会影响我的第二个对象上已经存在的数据。目标是在“父”对象的full_params对象文字中拥有一组基本默认值,并在“子”对象的default_params对象文字中拥有一些更具体的默认值。子对象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
}