借用父构造函数继承属性

在ES6前没有extends继承,通过构造函数+原型对象模拟实现继承,称作组合继承。

function Father(uname, age) {
            //this 指向父构造函数的对象实例
            this.uname = uname;
            this.age = age;
        }
        Father.prototype.money = function () {
            console.log(1000);
        }
        //2.子构造函数
        function Son(uname, age, score) {
            //this指向子构造函数对象实例
            Father.call(this, uname, age)
            this.score = score;
        }

在子构造函数中,通过Father.call(this)使子构造函数中this指向父构造函数Father实例对象,通过这种方法来继承父构造函数属性。

var son = new Son('刘德华', 18, 100);
console.log(son);

返回结果为,可以看到继承了Father中的uname,age。

但不能通过这种方法继承父构造函数中的原型对象,也不能下面的通过直接赋值操作完成

Son.prototype = Father.prototype;

这样虽然修改了子原型对象,也会导致 父原型对象一起变化。

想要继承原型对象可以借助Father的实例对象来完成,即:

Son.prototype = new Father();

通过这种方式,在修改或者新增子原型对象时,不会影响父原型对象;

Father.prototype.money = function () {
            console.log(1000);
        }
Son.prototype.exam = function () {
            console.log('考试');
        }
var son = new Son('刘德华', 18, 100);
console.log(son);
console.log(Father.prototype);

Son实例对象son会继承Father的money方法,但是Father的原型对象中不会新增exam方法

不过使用这种方法,会更改Son.prototype.constructor的指向,需要通过

Son.prototype.constructor = Son;

使其重新指向Son

 

posted @ 2021-08-27 16:48  mmsmd  阅读(44)  评论(0编辑  收藏  举报