1.ES5与ES6声明类比较
- ES5中声明一个类
let Animal = function(type){
this.type = type
}
Animal.prototype.eat = function(){
console.log("eat eat eat")
}
let cat = new Animal("cat")
let dog = new Animal("dog")
console.log(cat)
console.log(dog)
- ES6中声明一个类
class Animal{
constructor(type){
this.type = type
}
eat (){
console.log("eat eat eat")
}
}
let cat = new Animal("cat")
let dog = new Animal("dog")
console.log(cat)
console.log(dog)
从上面可以看出在ES6中心增加了一个class关键字来定义类,较ES5更加简便,但从上面两张图来看ES6与ES6是一样的。ES6中的class只是一个语法糖而已。
- ES5的类中声明类的静态方法
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
Animal.walk() //静态方法调用
console.log("eat eat eat")
}
Animal.walk = function () { //静态方法
console.log("I can Walk")
}
let dog = new Animal('dog')
dog.eat()
- ES6的类中声明类的静态方法
class Animal {
constructor(type) {
this.type = type
}
eat() {
Animal.walk() //静态方法调用
console.log("eat eat eat")
}
static walk (){ //静态方法
console.log("I can walk")
}
}
let cat = new Animal("cat")
cat.eat()
- ES5中的继承
ES5中的继承分为两部:第一步继承父类本身的属性和方法;第二部继承父类原型链上的方法。
let Animal = function (type) {
this.type = type
}
Animal.prototype.eat = function () {
console.log("eat eat eat")
}
let Dog = function(){
// 第一步:初始化父类的构造函数
Animal.call(this, 'dog')
this.run = function(){
console.log('i can run')
}
}
// 第二步:继承父类的原型
Dog.prototype = Animal.prototype
let dog = new Dog("dog")
dog.eat() // eat eat eat
- ES6中的继承
ES6中的类的继承比ES5简单很多,只需要在定义子类时使用extends关键字即可
class Animal {
constructor(type) {
this.type = type
}
eat() {
console.log("eat eat eat")
}
}
class Dog extends Animal {
constructor(type) {
super(type)
}
}
let dog = new Dog('dog')
dog.eat() //eat eat eat
2.ES6中的set和get
let _age = 1
class Animal{
constructor(type){
this.type = type
}
eat (){
console.log("eat eat eat")
}
get age(){
return _age
}
set age(val){
if(val < 5 && val>3){
_age = val
}
}
}
let cat = new Animal("cat")
let dog = new Animal("dog")
console.log(dog.age) //1
dog.age = 4;
console.log(dog.age) //4