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的国籍时,它也会改变我母亲的国籍。可能是什么原因?
答案 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)
由于原型是在对象定义的每个实例中共享的,所以你应该这样做:
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;
答案 2 :(得分:0)
要防止使用一个为原型指定属性 级别点和字符串分配。
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;