美文网首页
13.JavaScript-继承方式三

13.JavaScript-继承方式三

作者: Fl_来看看 | 来源:发表于2019-06-06 14:08 被阅读0次

上一篇12.继承方式二有这么一句话

还是有弊端:假如Person.prototype添加了新的方法,Student实例想用怎么办?没法呀

  • 主要通过下面两句话解决弊端(前提用了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");
            }
        }
        // 注意点: 要想使用Person原型对象中的属性和方法, 
        //那么就必须将Student的原型对象改为Person的原型对象才可以
        Student.prototype = Person.prototype;
        Student.prototype.constructor = Student;

        let stu = new Student("ww", 19, 99);
        console.log(stu.score);
        stu.say();
        stu.study();

这种方式还是有弊端的,问题出现在解决问题的语句上

Student.prototype = Person.prototype;
Student.prototype.constructor = Student;

有什么弊端?设Person.prototype为A,即Student.prototype 也为A,就是说Person原型对象和Student原型对象是同一个,同一个地址,而对象是引用类型,那么对Student.prototype设置constructor 为Student,即Person.prototype.constructor也为Student~!

解决方法看下一篇

相关文章

  • 13.JavaScript-继承方式三

    上一篇12.继承方式二有这么一句话 还是有弊端:假如Person.prototype添加了新的方法,Student...

  • 14.继承方式四

    上一篇13.JavaScript-继承方式三 这种方式还是有弊端的,问题出现在解决问题的语句上Student.pr...

  • 第十三章 类继承(4)c++的三种继承方式

    (四)c++的三种继承方式 c++有三种继承方式,分别是公有继承,私有继承和保护继承。 (1)公有继承 这是最常用...

  • 原型继承

    原型链的继承 1.第一种继承方式(原型链继承) 2.第二种继承方式(第二种继承方式) 3.第三种继承方式(组合继承)

  • JS中继承的方式

    讨论三种常用的继承方式: 组合继承 原型新对象继承 3 . 寄生继承

  • C++继承,静态成员,const成员

    继承 继承的方式有三种 公共继承 保护继承 私有继承 访问权限publicprotectedprivate对本类可...

  • JS对象和继承

    JS 对象创建的三种方式 字面量创建方式 系统内置构造函数方式 自定义构造函数 继承方式 for in 继承 原型...

  • 4期c++9月18号

    上午 一.继承 1.class 派生类名:继承方式 基类名 { 派生类中的新成员 } 三种继承方式:公有继承:pu...

  • js的继承方式

    js的继承方式 一、原型链继承 原型继承的缺点: 二. 构造函数继承 构造函数继承的缺点: 三. 组合式继承 组合...

  • 7、面向对象的程序设计3(《JS高级》笔记)

    三、继承 许多OO语言都支持两种继承方式:接口继承和实现继承。接口继承只继承方法签名,而实现继承则继承实际方法。由...

网友评论

      本文标题:13.JavaScript-继承方式三

      本文链接:https://www.haomeiwen.com/subject/xnayxctx.html