利用原型对象继承方法

首先清楚constructor属性所有的对象都可以访问constructor属性,该属性返回对象构造函数,返回值是对函数的引用,而不是函数的名称。

1.借用父构造函数继承属性,使用call()方法,改变this的指向。
代码验证
<script>
        // 1.借用父构造函数继承属性
        function Father(uname,age) {
            // this指向父构造函数的实例对象
            this.uname = uname;
            this.age = age; 
        }
        // 2.子构造函数
        function Son(uname1,age1) {
            // 子构造函数想要继承父亲的属性
            // 这里的this指向的是子构造函数函数,因为call方法修改了this的指向
            // uname1和age1是实参,传到Father这个构造函数里面
            Father.call(this,uname1,age1);
        }
        var son = new Son('郭富城',18);
        //输出结果相当于是使用了Father这个构造函数,参数名称是uname和age,而不是uname1和age1
        console.log(son);

</script>
2.利用原型对象继承
代码验证
 <script>
        // 1.借用父构造函数继承属性
        function Father(uname,age) {
            // this指向父构造函数的实例对象
            this.uname = uname;
            this.age = age; 
        }
        // 2.子构造函数
        function Son(uname1,age1,score) {
            // 子构造函数想要继承父亲的属性
            // 这里的this指向的是子构造函数函数,因为call方法修改了this的指向
            // uname和age是实参,传到Father这个构造函数里面
            Father.call(this,uname1,age1);
            this.score = score;
        }
        // 给父原型对象添加方法
        Father.prototype.money = function(){
            console.log('爸爸赚钱100');
        }
        // 这样直接赋值确实可以得到父原型对象的值,但是如果修改了子原型对象,父原型对象也会被修改
        // Son.prototype = Father.prototype;

        // new Father()实例化了对象,赋值给了子原型对象,原来的子原型对象就没有了
        // 需要用constructor指回原来的构造函数
        Son.prototype = new Father();
        Son.prototype.constructor = Son;
        // 子构造函数专门的方法
        Son.prototype.exam = function(){
            console.log('孩子要考试');
        }
        var son = new Son('郭富城',18);
        console.log(Son.prototype);
        console.log(Father.prototype);      

</script>
qwpSyD.png

这个真的好绕啊!!!!过几天再看一遍

posted @ 2022-03-26 10:17  Lindsay_jie  阅读(25)  评论(0)    收藏  举报