es5和es6中的继承和静态方法

ES5中的静态方法

function Person(name, age){
    this.name = name
    this.age = age
    this.run = function () {
        console.log(`${this.name}---${this.age}`)
    }
}

Person.work = function () {
    console.log('work')
}

var p = new Person('Carlo', 20) //实例方法是通过实例化来调用的
p.run()

Person.work()  //静态方法是通过类名直接调用

ES5中的继承方式

  • 对象冒充继承:没法继承原型链上面的属性和方法
function Person(name, age){
    this.name = name
    this.age = age
    this.run = function () {
        console.log(`${this.name}---${this.age}`)
    }
}

Person.prototype.work = function () {
    console.log('work')
}

function Web(name, age) {
    Person.call(this, name, age)
}

var p = new Web('Lily', 18)
p.run()  //Lily---18
p.work()  //TypeError: p.work is not a function
  • 原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参

function Person(name, age){
    this.name = name
    this.age = age
    this.run = function () {
        console.log(`${this.name}---${this.age}`)
    }
}

Person.prototype.work = function () {
    console.log('work')
}

function Web(name, age) {
}

Web.prototype = new Person()

var p = new Web('Lily', 18)
p.run()  //undefined---undefined
p.work()  //work

结合使用

function Person(name, age){
    this.name = name
    this.age = age
    this.run = function () {
        console.log(`${this.name}---${this.age}`)
    }
}

Person.prototype.work = function () {
    console.log('work')
}

function Web(name, age) {
    Person.call(this, name, age)
}

Web.prototype = new Person()


var p = new Web('Lily', 18)
p.run()  //Lily---18
p.work()  //work

ES6中的静态方法

class Person {
    constructor (name, age) {
        this._name = name
        this._age = age
    }

    getInfo () {
        console.log(`${this.name}---${this.age}`)
    }

    static run () {
        console.log('这是一个静态方法')
    }
}

Person.neural = '这也是一个静态方法'

let p = new Person()
Person.run()  //这是一个静态方法
console.log(Person.neural)  //这也是一个静态方法

ES6中的继承方式

class Person {
    constructor (name, age) {
        this._name = name
        this._age = age
    }

    getInfo () {
        console.log(`${this.name}---${this.age}`)
    }

    run () {
        console.log('run')
    }
}

class Web extends Person {
    constructor (name, age, gender) {
        super(name, age)
        this._gender = gender
    }

    getGender () {
        console.log(this._gender)
    }
}

let w = new Web('Lily', 18, 'girl')
w.getGender()  //girl

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值