這種方式還是有弊端的寒矿,問題出現(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也為Student~匀泊!
就是說,給 Student.prototype設(shè)置方法朵你,會(huì)影響到父類的原型對(duì)象各聘,父類的實(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原型對(duì)象的constructor屬性,
所以破壞了Person的三角戀關(guān)系
2.由于Person和Student的原型對(duì)象是同一個(gè),
所以給Student的元素添加方法, Person也會(huì)新增方法
*/
// 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將子類的原型對(duì)象修改為父類的實(shí)例對(duì)象
*/
// 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將子類的原型對(duì)象修改為父類的實(shí)例對(duì)象
報(bào)錯(cuò)撬呢,給 Student.prototype設(shè)置方法伦吠,不會(huì)影響到父類的原型對(duì)象妆兑,父類的實(shí)例也就訪問不到魂拦!
思考,這樣子就沒有弊端了嗎搁嗓?
Student.prototype = new Person();
Student.prototype.constructor = Student;
- new Person();芯勘,返回一個(gè)Object實(shí)例,因?yàn)樵趎ew Person()時(shí)腺逛,在Person內(nèi)部荷愕,new 了Object,設(shè)置構(gòu)造函數(shù)為Person棍矛,且返回Object實(shí)例安疗,所以Student.prototype.constructor ===Person(才有了第二句),
- new Person和Person原型對(duì)象的值肯定不一樣够委,所以Student.prototype.constructor = Student;是不會(huì)讓父類的實(shí)例對(duì)象訪問到的荐类!~