对象字面量与class
- 当属性与值的变量同名时。
const name = 'Tom'
const age = 22
//es5
var user = {
name: name,
age: age
}
//es6
var user = {
name,
age
}
- 除了属性之外,对象字面量写法中的方法也可以有简写方式。
//es6
var person = {
name,
age,
getName(){
return this.name
}
}
//es5
var person = {
name: name,
age: age,
getName: function getName(){
return this.name
}
}
- 在对象字面量中可以使用中括号作为属性,表示属性名也能是一个变量了。
const name = 'Tom'
const age = 22
const person = {
[name]: true,
[age]: true
}
- class
ES6为我们创建对象提供了新的语法糖,这就是Class语法。如果你对ES5中面向对象的方式比较熟悉的话,Class掌握起来也是非常迅速的,因为除了写法的不同,它并不会增加新的难以理解的知识点。我们先利用一个简单的例子来看看写法的不同。
// ES5
// 构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
// 原型方法
Person.prototype.getName = function() {
return this.name
}
// ES6
class Person {
constructor(name, age) { // 构造函数
this.name = name;
this.age = age;
}
getName() { // 原型方法
return this.name
}
}
babel会将ES6的写法编译成为利用Object.defineProperty实现的方式
除此之外,我们还需要特别注意在实际使用中的几种写法方式的不同,在下面的例子注释中,我说明了他们分别对应的ES5中的含义。
class Person{
//构造函数
constructor(name, age){
this.name = name,
this.age = age
},
//将方法添加到原型中
getName(){
return this.name
},
static a = 20 //等同于 Person.a = 20
c = 10 // 表示在构造函数中添加属性 在构造函数中等同于 this.c = 10
// 箭头函数的写法表示在构造函数中添加方法,在构造函数中等同于this.getAge = function() {}
getAge = () => this.age
}
箭头函数需要注意的仍然是this的指向问题,因为箭头函数this指向不能被改变的特性
- 继承 extends
class Person = {
constructor(name, age){
this.name = name
this.age = age
}
getName(){
return this.name
}
}
class Student extends Person{
constructor(name, age, gender, classes){
super(name, age)
this.gender = gender
this.classes = classes
}
getGender(){
return this.gender
}
}
我们只需要一个extends关键字,就可以实现继承了,不用像ES5那样去担心构造函数继承和原型继承,除此之外,我们还需要关注一个叫做super
的方法。
在继承的构造函数中,我们必须如上面的例子那么调用一次super方法,它表示构造函数的继承,与ES5中利用call/apply继承构造函数是一样的功能。