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