14.繼承方式四

上一篇13.JavaScript-繼承方式三

這種方式還是有弊端的,問題出現(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;是不會讓父類的實例對象訪問到的!~
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容