设置原型对象的字段会更改所有实例

时间:2016-08-24 08:41:33

标签: javascript object prototype

JSFiddle

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}
Person.prototype = {
    nationality : {
        type : ""
    },
    changeNationality:function(n){
        this.nationality.type = n;
    }
};

var myFather = new Person("John", "Doe", 50, "blue");

var myMother = new Person("Jane", "Doe", 50, "blue");

myMother.changeNationality("English");
myFather.changeNationality("German");

document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality.type + "<br/> My mother is " + myMother.nationality.type;

当我改变myFather的国籍时,它也会改变我母亲的国籍。可能是什么原因?

3 个答案:

答案 0 :(得分:1)

因为您在nationality级而不是prototype级别定义Person,这就是prototype的原因!这个想法是在所有类实例之间共享,否则每个实例都会有自己的每个方法的定义,使用更多的内存和潜在的不同行为。

尝试将nationality移动到构造函数:

function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.nationality = { type: "" };
}

答案 1 :(得分:1)

由于原型是在对象定义的每个实例中共享的,所以你应该这样做:

&#13;
&#13;
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.nationality = {
        type : ""
    };
}
Person.prototype = {
    
    changeNationality:function(n){
        this.nationality.type = n;
    }
};

var myFather = new Person("John", "Doe", 50, "blue");

var myMother = new Person("Jane", "Doe", 50, "blue");

myMother.changeNationality("English");
myFather.changeNationality("German");

document.getElementById("demo").innerHTML =
"My father is " + myFather.nationality.type + "<br/> My mother is " + myMother.nationality.type;
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

  

要防止使用一个为原型指定属性   级别点和字符串分配。

&#13;
&#13;
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
    this.changeNationality = function(n){
        this.nationalityType = n
    }
}

Person.prototype.nationalityType = 'default';

var myFather = new Person("John", "Doe", 50, "blue");

var myMother = new Person("Jane", "Doe", 50, "blue");
myMother.changeNationality("English");
myFather.changeNationality("German");
document.getElementById("demo").innerHTML =
"My father is " + myFather.nationalityType + "<br/> My mother is " + myMother.nationalityType;
&#13;
<p id="demo"></p>
&#13;
&#13;
&#13;