优化 大致 const his rip es6 ext 构造 create
javascript实现继承大致有如下5种方式:
第1种,通过构造函数实现继承
- function Parent() {
- this.name = ‘parent‘
- }
- function Child() {
- Parent.call(this)
- this.type = ‘child‘
- }
第2种,通过原型链实现继承
- function Parent() {
- this.name = ‘parent‘
- }
- function Child() {
- this.type = ‘child‘
- }
- Child.prototype = new Parent()
- Child.prototype.constructor = Child
第3种,组合第1种和第2种方式
- function Parent() {
- this.name = ‘parent‘
- }
- function Child() {
- Parent.call(this)
- this.type = ‘child‘
- }
- Child.prototype = new Parent()
- Child.prototype.constructor = Child
第4种,是对第3种的优化,也是推荐的方式
- function Parent() {
- this.name = ‘parent‘
- }
- function Child() {
- Parent.call(this)
- this.type = ‘child‘
- }
- Child.prototype = Object.create(Parent.prototype)
- Child.prototype.constructor = Child
第5种,使用es6语法
- class Parent {
- constructor() {
- this.name = ‘parent‘
- }
- }
- class Child extends Parent {
- constructor() {
- super() this.type = ‘child‘
- }
- }
谈谈javascript继承
来源: http://www.bubuko.com/infodetail-2328668.html