JavaScript的继承

JavaScript的继承

JavaScript没有继承,而是通过原型链访问构造函数的原型对象上的方法,为了方便叙述,称为继承
构造函数继承(对象冒充继承)
原理:使用call,apply,bind改变构造函数内的this指向,从而继承构造函数内的属性和方法

function Cat(n,c){
    this.name = n;
    this.color = c;
    this.say = function (){
        console.log('卖萌~');
    }
}
Cat.prototype.type = 'animal';
Cat.prototype.skill = function (){
    alert('抓老鼠');
}


function Dog(f,n,c){
    this.food = f;
    Cat.call(this,n,c);//对象冒充继承
}
Dog.prototype.eat = function (){
    alert(this.food);
}
var dog1 = new Dog('shi','大黄','yellow');

直接在创建第二个构造函数内普通调用第一个构造函数并改变this指向,为第二个构造函数的实例对象添加属性和方法
注:只能继承构造函数内的属性和方法,不能继承原型对象的属性和方法

原型继承–创建对象继承

// 原型继承 原型链接
function Cat(n,c){
    this.name = n;
    this.color = c;
    this.say = function (){
        console.log('卖萌~');
    }
    return {a:1,b:2}
}
Cat.prototype.type = 'animal';
Cat.prototype.skill = function (){
    alert('抓老鼠');
}
function Dog(f){
    this.food = f;
}
Dog.prototype = Object.create(Cat.prototype);// 寄生继承
Dog.prototype.eat = function (){
    alert(this.food);
}
var dog1 = new Dog('shi','大黄','yellow');

又叫做寄生继承,Object.create(obj)的作用是创建一个空的对象并把原型指针__proto__指向obj
只能继承原型对象,不能继承构造函数内的属性和方法,如果需要都继承,两者结合
拷贝继承
将需要继承的对象拷贝一份放入对象中,虽然麻烦,但是简单

两者结合的继承

        // 构造函数继承+原型继承
        // 父类
        function Fn(a , b){
            this.name = a;
            this.age = b
        }
        Fn.prototype={
            constructor:Fn,
            sayHi:function(){
                console.log('hi , nihao');
            }
        }
        // 子类
        function Son(a , b){
            // 改变this指向,并传递参数
            Fn.call(this,a,b)
            // 自己的属性
            this.son = 'son';
        }
        //创建一个空对象,原型指向Fn.prototype
        Son.prototype = Object.create(Fn.prototype)
        // 如果子类添加函数,只能一个一个的添加
        Son.prototype.sayHello=function(){
            console.log('hello');
        }
        
        var son1 = new Son;

刚简单的ES6继承
https://blog.csdn.net/htcvive/article/details/107619729

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值