14.继承方式四

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

这种方式还是有弊端的,问题出现在解决问题的语句上
Student.prototype = Person.prototype;
Student.prototype.constructor = Student;
有什么弊端?设Person.prototype为A,即Student.prototype 也为A,就是说Person原型对象和Student原型对象是同一个,同一个地址,而对象是引用类型,那么对Student.prototype设置constructor 为Student,即Person.prototype也为Student~!

就是说,给 Student.prototype设置方法,会影响到父类的原型对象,父类的实例也就访问到了

解决:

将     Student.prototype = Person.prototype;【问题出现在这里嘛】
       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的三角恋关系
        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在子类的构造函数中通过call借助父类的构造函数
        1.2将子类的原型对象修改为父类的实例对象
        */
        // let stu = new Student("ww", 19, 99);
        // console.log(stu.score);
        // stu.say();
        // stu.study();

1.js中继承的终极方法

  • 1.1在子类的构造函数中通过call借助父类的构造函数
  • 1.2将子类的原型对象修改为父类的实例对象

报错,给 Student.prototype设置方法,不会影响到父类的原型对象,父类的实例也就访问不到!


5.jpg

思考,这样子就没有弊端了吗?

Student.prototype = new Person();
Student.prototype.constructor = Student;
  • new Person();,返回一个Object实例,因为在new Person()时,在Person内部,new 了Object,设置构造函数为Person,且返回Object实例,所以Student.prototype.constructor ===Person(才有了第二句),
  • new Person和Person原型对象的值肯定不一样,所以Student.prototype.constructor = Student;是不会让父类的实例对象访问到的!~
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容