ES5/ES6 除了写法之外还有什么区别?

区别如下:

1、class 声明会提升,但是不会初始化赋值
const bar = new Bar(); // 2
funciton Bar(){
	return 2;
}

const foo = new Foo(); // ReferenceError: Foo is not defined
class Foo{
	constructor(){
		this.foo = 42;
	}
}
2、class 声明内部会启用严格模式
function Bar(){
	bar = 42; // 不会报错
}

class Foo{
	constructor(){
		foo = 42; // ReferenceError: fol is not defined
	}
}
3、class 的所有方法(包括静态方法和实例方法)都是不可枚举的
function Bar(){
	this.bar = 42;
}
Bar.answer = function(){
	return 42;
}
Bar.prototype.getAge = funtion(){
	return 42;
}
console.log(Bar.keys(Bar)); // ['answer']
console.log(Bar.keys(Bar.prtotypee)); // ['getAge']

class Foo{
	constructor(){
		this.foo = 42;
	}
	static answer(){
		return 42;
	}
	getAge(){
		return 42;
	}
}
console.log(Bar.keys(Foo)); // []
console.log(Bar.keys(Foo.prtotypee)); // []

4、class 所有的方法都没有原型对象 prototype,也没有 [[constructor]],不能使用 new 调用
function Bar(){
	this.bar = 42;
}
Bar.answer = function(){
	return 42;
}
Bar.prototype.getAge = funtion(){
	return 42;
}
const bar = new Bar();
const ageCount = new Bar.getAge(); // 不会报错

class Foo{
	constructor(){
		this.foo = 42;
	}
	static answer(){
		return 42;
	}
	getAge(){
		return 42;
	}
}
const foo = new Foo();
const ageGet = new Foo.getAge();// TypeError: Foo.getAge is not a constructor
5、必须使用 new 调用 class
class Foo{
	constructor(){
		this.foo = 42;
	}
	static answer(){
		return 42;
	}
	getAge(){
		return 42;
	}
}
const foo = new Foo();
6、class 内部无法重写类名
function Bar() {
  Bar = 'Baz'; // it's ok
  this.bar = 42;
}
const bar = new Bar();
// Bar: 'Baz'
// bar: Bar {bar: 42}  
 
class Foo {
  constructor() {
    this.foo = 42;
    Foo = 'Fol'; // TypeError: Assignment to constant variable
  }
}
const foo = new Foo();
Foo = 'Fol'; // it's ok
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值