面向对象之继承

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    <script>

        /**

         * @param 子类

         * @param 父类

         * */

        function extend(child, parent) {

            function f() { }

            f.prototype = parent.prototype;

            child.prototype = new f();

            child.prototype.constructor = child;

        }

        // Object.prototype.foot = 2;

        /*

            空对象,几乎不占内存

            修改Student的prototype对象,不会影响到Person的prototype对象

        */

        /* 父类 */

        function Person() { }

        Person.prototype.head = 1;

        Person.prototype.foot = 2;

        /* 子类想继承父类的属性 */

        function Student() { }

        /* 新建一个空对象 */

        //    function f(){}

        //    /* 把父类的原型直接赋值给空对象的原型上 */

        //    f.prototype = Person.prototype;

        //    /* 把空对象的实例化对象 给到子类的原型上  */

        //    Student.prototype = new f();

        //    /* ★constructor构造器都是指向自己的 */

        //    Student.prototype.constructor = Student;

        extend(Student, Person)

        let stu1 = new Student();

        console.log(stu1.foot);

        console.log(stu1);

        /* 不会影响到Person的prototype对象 */

        // Student.prototype.age = 30;

        //    let p = new Person();

        //    console.log(p);

        /* 原型链就是一层一层向上找的过程  */

        /* 原型链继承就是利用了上面这种特性 */

        /* 写一个类 Car color price 属性 */

        /* 类 Bmw 继承Car的所有属性 并实例化Bmw这个类

        写个方法可以把 color 和 price 打印到页面上 */

        function Car() {

        }

        Car.prototype.color = '白色'

        Car.prototype.price = '100w'

        // function f(){}

        // f.prototype = Car.prototype;

        // Bmw.prototype = new f();

        // Bmw.prototype.constructor = Bmw;

        extend(Bmw, Car)

        function Bmw() {

            this.print = function () {

                document.write(`${this.color}--${this.price}`);

            }

        }

        let b1 = new Bmw();

        b1.print();

    </script>

</body>

</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容