上一篇12.繼承方式二有這么一句話
還是有弊端:假如Person.prototype添加了新的方法,Student實(shí)例想用怎么辦?沒法呀
- 主要通過下面兩句話解決弊端(前提用了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");
}
}
// 注意點(diǎn): 要想使用Person原型對(duì)象中的屬性和方法,
//那么就必須將Student的原型對(duì)象改為Person的原型對(duì)象才可以
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
let stu = new Student("ww", 19, 99);
console.log(stu.score);
stu.say();
stu.study();
這種方式還是有弊端的,問題出現(xiàn)在解決問題的語句上
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
有什么弊端?設(shè)Person.prototype為A,即Student.prototype 也為A,就是說Person原型對(duì)象和Student原型對(duì)象是同一個(gè),同一個(gè)地址,而對(duì)象是引用類型,那么對(duì)Student.prototype設(shè)置constructor 為Student,即Person.prototype.constructor也為Student~!
解決方法看下一篇