ES6新特性——10.class

新旧用法

ES5:
function Person(name, age){
	this.name = name;
	this.age = age;
}
Person.prototype.sayName = function(){
	return this.name
}
ES6:
class Person{
	//实例化的时候会立即调用
	constructor(name, age){
		this.name = name;
		this.age = age;	
	} //后面没有逗号,因为这是方法
	sayName(){
		return this.name	
	}//后面没有逗号,因为这是方法
	sayAge(){
		return this,age	
	}//后面没有逗号,因为这是方法
}

或者:
class Person{
	//实例化的时候会立即调用
	constructor(name, age){
		this.name = name;
		this.age = age;	
	} //后面没有逗号,因为这是方法
	Object.assign(Person.prototype, {
		sayName(){
		return this.name	
	},
	sayAge(){
		return this,age	
	},	
	})
}

1.匿名类

let Example = class {
    constructor(a) {
        this.a = a;
    }
}

2.命名类

let Example = class Example {
    constructor(a) {
        this.a = a;
    }
}

不可重复声明。
类定义不会被提升,这意味着,必须在访问前对类进行定义,否则就会报错。

类中方法不需要· function关键字。

3.constructor 方法

constructor方法是类的默认方法,创建类的实例化对象时被调用。

class Example{
    constructor(){
      console.log('我是constructor');
    }
}
new Example(); // 我是constructor

4.原型方法,静态方法,实例方法

4.1静态方法

class Example{
    static sum(a, b) {
        console.log(a+b);
    }
}
Example.sum(1, 2); // 3

4.2原型方法

class Example {
    sum(a, b) {
        console.log(a + b);
    }
}
let exam = new Example();
exam.sum(1, 2); // 3

4.3实例方法

class Example {
    constructor() {
        this.sum = (a, b) => {
            console.log(a + b);
        }
    }
}

5实例化

·class 的实例化必须通过 new关键字。

6.继承

class Person{
	//实例化的时候会立即调用
	constructor(name, age){
		this.name = name;
		this.age = age;	
	} //后面没有逗号,因为这是方法
	sayName(){
		return this.name	
	}//后面没有逗号,因为这是方法
	sayAge(){
		return this,age	
	}//后面没有逗号,因为这是方法
}
class child entends Person{
	constructor(name,age, length){
		super(name, age); //相当于Person.call(this, name, age)
		this.height = height;	
	}
}

1重写父类方法

class Person{
	//实例化的时候会立即调用
	constructor(name, age){
		this.name = name;
		this.age = age;	
	} //后面没有逗号,因为这是方法
	sayName(){
		return this.name	
	}//后面没有逗号,因为这是方法
	sayAge(){
		return this,age	
	}//后面没有逗号,因为这是方法
}
class child entends Person{
	constructor(name,age, length){
		super(name, age); //相当于Person.call(this, name, age)
		this.height = height;	
	}
	//重写父类方法
	sayName(){
		return super.name + super.age
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值