ES5声明一个类
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
console.log('eat')
}
ES6声明一个类
class Animal {
// 构造函数
constructor () {
this.type = type
}
eat () {
console.log('eat')
}
}
用class声明类只是ES5声明类的一个语法糖
getter setter可以控制属性的读写
let _age = 1 // 相当于私有属性,外部访问不到 class Animals { constructor (kind) { this.kind = kind } get age () { return _age } set age(val) { _age = val } shout () { console.log('...') } } let dog = new Animals('dog') console.log(dog.age) dog.age = 2 console.log(dog.age)
类的静态方法
class Animal { constructor (kind) { this.kind = kind } static shout () { console.log('这里是类的静态方法') } } Animal.shout() // 在ES5里就是 Animal.shout = function () {}
类的继承
// ES5 let Animal = function (kind) { this.kind = kind } Animal.prototype.shout = function () { console.log('...') } let Dog = function () { // 初始化父类的构造函数 Animal.call(this, 'dog') } Dog.prototype = Animal.prototype
// ES6 class Animal { constructor (kind) { this.kind = kind } static shout () { console.log('这里是类的静态方法') } } class Dog extends Animal { constructor (kind, color) { super(kind) this.color = color } } let dog = new Dog('dog', 'white') console.log(dog.kind) console.log(dog.color) dog white