JS继承4

2020-10-28 10:37:25 浏览数 (1)

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        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();
    </script>
</body>
</html>

0 人点赞