方法 1 正常,方法二没有声明 sayName 动态模型不能用字面量是吗?
//方式一
function Person(name){
this.name = name;
if(typeof this.sayName != "function") {
Person.prototype.sayName = function() {
alert(this.name);
}
}
}
var person1 = new Person("xiaoming");
person1.sayName();
//方式二
function Person(name){
this.name = name;
if(typeof this.sayName != "function") {
Person.prototype={ //这里不能用字面量是吗?
sayName:function() {
alert(this.name);
}
}
}
}
var person1 = new Person("xiaoming");
person1.sayName();
1
xingo 2016 年 11 月 21 日
你在构造时把 Person 原型都替换掉了,那 person1 的原型当然就不是 Person 的实例啦
https://ooo.0o0.ooo/2016/11/21/58330c6c69584.png |