再学JavaScript ES(6-10)全版本语法大全(5)- Class 基础

1 Class

1.1 ES5 声明一个类

let Animal = function (type) { 
    this.type = type
    this.eat = function(){}
}

let dog = new Animal("dog")
let monkey = new Animal('monkey')

console.log(dog)
console.log(monkey)

在这里插入图片描述


let Animal = function (type) { 
    this.type = type
}

Animal.prototype.eat = function () {
    console.log('eat 方法执行')
}

let dog = new Animal('dog')
let monkey = new Animal('monkey')

console.log(dog)
console.log(monkey)

// monkey.eat = function () {
//     console.log('eat')
// }


monkey.constructor.prototype.eat = function () {
    console.log('error')
}

dog.eat()
monkey.eat()


在这里插入图片描述

1.2 ES6

class Animal{
    constructor(type) {
        this.type = type;
    }

    eat() {
       console.log('eat food')
    }

}

let dog = new Animal('dog')
let cat = new Animal('cat')

console.log(dog)
console.log(cat)

2 读写属性

class Animal {
    constructor(type) {
        this.type = type
    }

    // 加上get 是一个属性
    get age() {
        return 666
    }

    set age(val) {
        this.realAge = val
    }

    eat() {
        console.log("eat food")
    }
}

let dog = new Animal('dog')
console.log(dog.age)

dog.age = 20
console.log(dog.realAge)

在这里插入图片描述

3 static method - 如何操作方法

  • 如果这个方法依赖于实例对象的属性或者方法,那么这个方法必须定义为类的实例对象方法
  • 类的静态方法拿不到当前的实例对象

3.1 ES5

let Animal = function (type) {
    this.type = type
}

Animal.prototype.eat = function () { 
    Animal.work()
    console.log("eat food")
}

// 静态方法
Animal.work = function () { 
    console.log("work")
}

let dog = new Animal("dog")
dog.eat()

在这里插入图片描述

3.2 ES6

class Animal {
    constructor(type) {
        this.type = type
    }

    eat() {
        Animal.walk()
        console.log("eat food")
    }

    static walk() { 
        console.log('walk')
    }
}

let dog = new Animal("dog")
dog.eat()

4 如何继承一个类

4.1 ES5

let Animal = function (type) {
    this.type = type
}

Animal.prototype.eat = function () {
    Animal.work()
    console.log("eat food")
}

// 静态方法
Animal.work = function () {
    console.log("work")
}

// 继承
let Dog = function (type) { 
    // 执行父类的构造函数
    Animal.call(this, 'dog')
    
    // Dog自己的实例对象挂载一些方法
    this.run = function () { 
        console.log("Dog can run")
    }
}

// 原型链,引用类型
Dog.prototype = Animal.prototype


let dog = new Dog("dog")
dog.eat()

4.2 ES6

class Animal {
    constructor(type) {
        this.type = type
    }

    eat() {
        Animal.walk()
        console.log("eat food")
    }

    static walk() { 
        console.log('walk')
    }
}

// 如果子类的构造函数是空的,可以不写
class Dog extends Animal {
    constructor(type) {
        super(type)
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页