4、ES5 类定义,继承

1、ES5类定义、静态方法、原型链的使用

1ES5 里面的类、构造方法、属性、实例方法及静态方法
    function Animal(name,age) {
        this.name=name;
        this.age=age;

        //1.1、构造函数里面的方法
        this.run=function () {
            console.log(this.name+"正在跑...");
        }
    }
    //1.2、原型链上添加方法
    Animal.prototype.say=function(){
        console.log("姓名:"+this.name+",年龄:"+this.age);
    };
    //1.3、静态方法,不需要实例对象调用,必须添加到类上
    Animal.toString=function(){
        console.log('这里是静态方法...');
    };
    //1.4、原型链上添加属性
    Animal.prototype.birthday='11/29';

    let taidi=new Animal("taidi",2);
    console.log(taidi.age);
    taidi.run();
    taidi.say();
    Animal.toString();

    let caroon=new Animal("caroon",1);
    caroon.birthday='5/6';
    console.log(taidi.birthday);//11/29
    console.log(caroon.birthday);//5/6

2、类继承

ES5 里面使用继承方法:

  1. 对象冒充继承
  2. 原型链继承
  3. 对象冒充+原型链继承(通常使用)

2.1、对象冒充继承

对象冒充继承只能够继承构造方法中的属性和方法,不能够继承原型链上的属性和方法

//2.1、对象冒充继承
    function Animal(name,age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(this.name + "正在跑...");
        }
    }
    Animal.prototype.say=function(){
        console.log("姓名:"+this.name+",年龄:"+this.age);
    };

    //对象冒充继承
    function Bird(name,age) {
        //对象冒充用call或apply
        Animal.call(this,name,age);
    }

    let dayan=new Bird("dayan",1);
    dayan.run();
    //对象冒充继承只能够继承构造函数里面的属性和方法,原型链上属性和方法不能够继承
    dayan.say();//报错

2.2、原型链继承

原型链继承可以继承属性和方法,但是没有办法给父类构造函数传参

function Animal(name,age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(this.name + "正在跑...");
        }
    }
    Animal.prototype.say=function(){
        console.log("姓名:"+this.name+",年龄:"+this.age);
    };

    function Bird(name,age) {
    }
    // 原型链继承 2种写法
    //Bird.prototype=Animal.prototype;
    Bird.prototype=new Animal();

    //方法和属性可有继承,但是没有办法给父类构造函数传参
    let dayan=new Bird("dayan",1);
    dayan.run();
    dayan.say();// 姓名:undefined,年龄:undefined

2.3、通常采用对象冒充+原型链继承

function Animal(name,age) {
        this.name = name;
        this.age = age;
        this.run = function () {
            console.log(this.name + "正在跑...");
        }
    }
    Animal.prototype.say=function(){
        console.log("姓名:"+this.name+",年龄:"+this.age);
    };

    function Bird(name,age) {
        //对象冒充继承
        Animal.apply(this,[name,age]);
    }
    // 原型链继承 2种写法
    //Bird.prototype=Animal.prototype;
    Bird.prototype=new Animal();

    //方法和属性可有继承,但是没有办法给父类构造函数传参
    let dayan=new Bird("dayan",1);
    dayan.run();
    dayan.say();// 姓名:undefined,年龄:undefined
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值