上一篇12.继承方式二有这么一句话
还是有弊端:假如Person.prototype添加了新的方法,Student实例想用怎么办?没法呀
- 主要通过下面两句话解决弊端(前提用了call,看上一篇继承方式二):
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
function Person(myName, myAge) {
this.name = myName; // stu.name = myName;
this.age = myAge; // stu.age = myAge;
// return this;
}
Person.prototype.say = function () {
console.log(this.name, this.age);
}
function Student(myName, myAge, myScore) {
Person.call(this, myName, myAge);
this.score = myScore;
this.study = function () {
console.log("day day up");
}
}
// 注意点: 要想使用Person原型对象中的属性和方法,
//那么就必须将Student的原型对象改为Person的原型对象才可以
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
let stu = new Student("ww", 19, 99);
console.log(stu.score);
stu.say();
stu.study();
这种方式还是有弊端的,问题出现在解决问题的语句上
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
有什么弊端?设Person.prototype为A,即Student.prototype 也为A,就是说Person原型对象和Student原型对象是同一个,同一个地址,而对象是引用类型,那么对Student.prototype设置constructor 为Student,即Person.prototype.constructor也为Student~!
解决方法看下一篇
网友评论