原型链 - 在一个对象上设置键会影响兄弟对象吗?

时间:2012-12-21 01:37:34

标签: javascript google-apps-script

我正在开发涉及继承和原型链的第一个JS项目,我很困惑为什么创建一个具有特定数据的对象会影响我的第二个对象上已存在的数据。 目标是在" parent"中的 full_params 对象文字中设置一组基本默认值。对象,并在" child"中的 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
}

1 个答案:

答案 0 :(得分:1)

您已将此父级的具体实例与此行绑定为子类的原型:

specificRequest.prototype = new baseRequest

相反,根本不要实例化父类:

specificRequest.prototype = Object.create( baseRequest.prototype );

此外,在构造子实例时调用super()等效项:

function specificRequest(mySKUList) {
     baseRequest.call( this );

     ...
}

请使用UpperCase启动构造函数名称。

相关问题