Skip to content

避免原型链使用过程中的属性共享问题 #4

@codemakesense

Description

@codemakesense

在使用原型链过程中,如果同一个原型对象有不同的实例对象,那么无法在不影响其他实例对象的情况下,给这个原型对象的构造函数传递参数,情况如下:

function Case() {
    this.color = ["red","green"];
}

function OtherCase() {}

OtherCase.prototype = new Case();

var instance1 = new OtherCase();
instance1.color.push("blue");
var instance2 = new OtherCase();
console.log(instance2.color);    //"red,green,blue"
console.log(instance1.color);    //"red,green,blue"

就如上面所示,可能目的只是往instance1的原型链上的color属性插入一个"blue"字符串,但是同时也影响了共用同一个原型对象的instance2。

解决办法就是使用call()或者apply()方法在函数内部调用原型对象的构造函数。

function Case() {
    this.color = ["red","green"];
}

function OtherCase() {
    Case.apply(this);    //继承了Case
};

var instance1 = new OtherCase();
instance1.color.push("blue");
var instance2 = new OtherCase();
console.log(instance2.color);    //“red,green”
console.log(instance1.color);    //"red,green,blue"

如上面,在函数内部直接调用Case原型的构造函数,使OtherCase的每个实例都有自己的color属性。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions