类的创建和继承

类的创建

  1. es6中采用class关键字进行类的创建
  2. es5中采用构造函数和原型对象的方式进行类的创建
//es6
class Singer {
            //属性
            constructor(sname, sage) {
                this.sname = sname;
                this.sage = sage;
            }
            // 方法
            sing(song) {
                console.log(this.sname + "演唱" + song);
            }
        }
        var jn= new Singer ('Jennie');
        nw.jn("solo");
        console.log(jn);
//es5
function Singer(){
	//属性
	this.sname = sname;
    this.sage = sage;
}
//方法
Singer.prototype.sing=function(song){
	console.log(this.sname + "演唱" + song);
}

类的继承

  1. es6中使用extends关键字
class Son extends Father{}
        class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            // 计算加法
            sum() {
                return this.x + this.y;
            }
        }
        // 继承用extends关键字
        // 子类继承父类 子类可以使用父类的属性和方法,同时子类还能自己扩展的属性和方法
        class Son extends Father {
            // 子类要想使用父类的构造函数 必须用super()
            constructor(x, y) {
                // 把参数传到父类的构造器的参数里
                // 这里是把子类的两个参数传到父类的构造函数里了
                super(x, y); // 必须要写在第一行 也就是子类的this之前
                this.x = x;
                this.y = y;
            }
            less() {
                return this.x - this.y;
            }
        }
        var father = new Father(2, 3);
        var son = new Son(5, 8);
        // 子类自己的方法
        console.log(son.sum());
        // 子类继承了父类的加法
        console.log(son.less());
  1. es5中:原型链继承、构造继承、组合继承、寄生式继承
/*
--原型链继承:子类的原型对象等于new一个父类的实例对象。
特点:基于原型链,既是父类的实例,也是子类的实例
缺点:无法实现多继承
*/
function Cat(){ }
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';


/*--构造继承:使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)
特点:可以实现多继承
缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法。
*/
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}


/*
--组合继承:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用。
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值