這種方式還是有弊端的,問題出現(xiàn)在解決問題的語句上
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
有什么弊端?設(shè)Person.prototype為A,即Student.prototype 也為A,就是說Person原型對象和Student原型對象是同一個,同一個地址,而對象是引用類型,那么對Student.prototype設(shè)置constructor 為Student,即Person.prototype也為Student~!
就是說,給 Student.prototype設(shè)置方法,會影響到父類的原型對象,父類的實例也就訪問到了!
解決:
將 Student.prototype = Person.prototype;【問題出現(xiàn)在這里嘛】
Student.prototype.constructor = Student;
改成: Student.prototype = new Person();
Student.prototype.constructor = Student;
function Person(myName, myAge) {
// let per = new Object();
// let this = per;
// this = stu;
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");
}
}
/*
弊端:
1.由于修改了Person原型對象的constructor屬性,
所以破壞了Person的三角戀關(guān)系
2.由于Person和Student的原型對象是同一個,
所以給Student的元素添加方法, Person也會新增方法
*/
// Student.prototype = Person.prototype;
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.run = function(){
console.log("run");
}
let per = new Person();
per.run();
/*
1.js中繼承的終極方法
1.1在子類的構(gòu)造函數(shù)中通過call借助父類的構(gòu)造函數(shù)
1.2將子類的原型對象修改為父類的實例對象
*/
// let stu = new Student("ww", 19, 99);
// console.log(stu.score);
// stu.say();
// stu.study();
1.js中繼承的終極方法
- 1.1在子類的構(gòu)造函數(shù)中通過call借助父類的構(gòu)造函數(shù)
- 1.2將子類的原型對象修改為父類的實例對象
報錯,給 Student.prototype設(shè)置方法,不會影響到父類的原型對象,父類的實例也就訪問不到!

5.jpg
思考,這樣子就沒有弊端了嗎?
Student.prototype = new Person();
Student.prototype.constructor = Student;
- new Person();,返回一個Object實例,因為在new Person()時,在Person內(nèi)部,new 了Object,設(shè)置構(gòu)造函數(shù)為Person,且返回Object實例,所以Student.prototype.constructor ===Person(才有了第二句),
- new Person和Person原型對象的值肯定不一樣,所以Student.prototype.constructor = Student;是不會讓父類的實例對象訪問到的!~