本文共 1007 字,大约阅读时间需要 3 分钟。
Class 可以通过
extends
关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。
class Human { constructor(name) { this.name = name } run(mile) { console.log(`我每小时能跑${ mile}`) } static hello() { console.log('hello world'); } } class Man extends Human { constructor(name, age) { this.age = age // Uncaught ReferenceError (在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,基于父类实例,只有super方法才能调用父类实例。) super(name) // 调用父类的constructor(name) this.age = age } } let man = new Man('小王', 22) console.log(man.name) // 小王 console.log(man.age) // 22 man.run(111) // 我每小时能跑111 man.hello() // hello world
注意:
转载地址:http://utri.baihongyu.com/