首页>>新闻中心>>ES6学习方法

ES5类的继承

来源: 本站    发布时间: 2021-02-22 17:05    阅读次数:

//ES5 继承
    function People(name, age){
        console.log(this) //这里面的this就是这个对应实例化对象
        //实例属性是定义在构造函数里面的
        this.name = name
        this.age = age
        People.count ++
    }
    // 实例方法
    People.prototype.showName = function (){
        console.log(`我的名字叫做${this.name}`)
    }
    //静态属性 是直接定义在类里面的
    People.count = 0
    // 静态方法
    People.getCount = function () {
        console.log(this) //这里指的是构造函数不是实例化对象
        console.log(this.age) // undefined
        console.log(`实例化的次数${People.count}`)
    }
    let  p1 = new People("Yangang", 16)
    let  p2 = new People("Yang", 20)
    p1.showName()
    //console.log(p2)

    let str = new String('Yang') //实例化字符串
    let arr = new Array(1, 2, 3)
    console.log(arr)
    let obj = new Object()
    obj.name = "Yangang"
    console.log(People.count) //直接类.属性值就可以得到对应的值
    People.getCount()
    //父类
    function Animal(name) {
        this.name = name
    }
    Animal.prototype.showName = function () {
        console.log(`动物的名字${this.name}`)
    }
    //子类
    function Dog(name, color) {
        Animal.call(this, name)
        this.color = color
    }
    Dog.prototype = new Animal() //原型继承
    Dog.prototype.constructor = Dog  //原型继承 但是需要把构造函数只会子类
    let dog = new Dog("旺财", "黑色")

    console.log(dog)
    dog.showName()
一起设计吧
BACK