美文网首页
组合继承(属性和方法)

组合继承(属性和方法)

作者: JSONYUAN | 来源:发表于2019-03-05 14:19 被阅读0次

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>

    </body>
    </html>
    <script>

    /**
     *
     *      组合继承
     *          call            继承属性
     *          prototype       继承方法
     *
     * */
    
    /* Person 构造函数 */
    function Person(name, age) {
        this.name = name;
        this.age = age;
    }
    
    Person.prototype.sayHi = function () {
        console.log('我是' + this.name);
    };
    
    Person.prototype.sayAge = function () {
        console.log('我今年' + this.age);
    };
    
    
    // 学生对象和人对象其实有很多重复
    // 所以我们考虑 <学生对象> 从 <人对象> 上<继承>过来一些基本的属性
    function Student(name, age, classNo) {
        /*
         *    call (打电话)借用一下 Person 构造函数
         *       第一个参数:调用该函数的那个对象
         *       后面的参数:作为实参传过去
         **/
        Person.call(this, name, age);     // 借用构造函数只能借用属性
        this.classNo = classNo;
    }
    
    /* 改变1 →: 尽管是空对象,但是空对象也有原型,间接继承了原型的方法  */
    // new Person()   实例化一个空对象,其实我们不是用空对象的属性,而是用了对象的原型
    Student.prototype = new Person();
    /* 改变2 →: 这行代码写不写都不影响继承,写了显得更专业,更规范  */
    // 由于上一行代码把原型改变了,constructor 没了,所以我们人为再添加一个 constructor
    Student.prototype.constructor = Student;
    
    // console.log(Student.prototype);
    
    var p1 = new Person('大树', 48);
    var stu1 = new Student('小成', 18, 313);
    
    
    // 后面给 Person 添加的方法,看看后面能不能调用
    Person.prototype.say666 = function(){
        console.log(666);
    };
    
    console.log(p1);
    console.log(stu1);
    stu1.sayAge();
    
    /*
    *     Student 的原型方法继承自 Person
    *         p1 能调用 say666,sayHi,sayAge
    *         stu1 也能调用 say666,sayHi,sayAge
    * */
    p1.say666();
    stu1.say666();
    
    console.log(stu1 instanceof Student);   // true
    console.log(stu1 instanceof Person);    // true
    console.log(stu1 instanceof Object);    // true
    

    </script>

    相关文章

      网友评论

          本文标题:组合继承(属性和方法)

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