目录
类在ES5中的写法
// 定义动物类
function Animal(name) {
// 实例属性
this.name = name
Animal.count++
}
// 实例方法
Animal.prototype.showName = function() {
console.log('这个动物的名字是' + this.name)
}
// 静态属性
Animal.count = 0
// 静态方法
Animal.getCount = function() {
console.log('当前有' + Animal.count + '只动物')
}
// ES5中如何继承父类
function Dog(name,disposition) {
// 通过call方法把this指向Dog,并且这里只继承了父类的属性!!!
Animal.call(this,name)
this.disposition = disposition
}
// 怎么继承父类的方法呢?
// Dog.prototype = Animal.prototype 这个写法有一定的问题,因为这样写可能会改变父类的原型对象
Dog.prototype = new Animal()
// Dog的构造函数要改回来
Dog.prototype.constructor = Dog
类在ES6中的写法
class Animal {
constructor(name) {
this.name = name
this._sex = -1
// 这里的this._sex不能写成this.sex,因为在set方法的触发条件是this.sex被改变,如果写成this.sex,那么在修改其值时会进入死循环
Animal.count++
}
// 什么时候用get和set来获取、修改实例属性?当实例属性有业务操作的时候
get sex() { // sex是实例属性
if (this._sex === 1) {
return 'male'
} else if (this.sex === 0) {
return 'female'
} else {
return 'error'
}
}
set sex(val) {
if (val === 0 || val === 1) {
this._sex = val
}
}
// 实例方法
showName() {
console.log(this.name)
}
// 静态方法
static getCount() {
console.log(Animal.count)
}
}
Animal.count = 0
// 继承 直接一步到位
class Dog extends Animal {
constructor(name,area) {
super(name)
this.area = area
}
showArea() {
console.log(this.area)
}
}
let dog1 = new Dog('Bob','area1')
dog1.sex = 1
console.log(dog1.sex)
dog1.showName()
dog1.showArea()
通过对比可以发现ES6类的写法方便的不是一点两点,但我们要知道的是class其实是语法糖