JavaScript 继承是面向对象编程中常见的概念,本篇文章主要介绍了以下五种继承方式:原型继承、借用构造函数继承、组合继承、寄生组合式继承、class继承。
原型继承
原型继承是指通过 prototype
对象的原型链进行继承。子类的 prototype
原型链指向了父类的实例,从而实现继承。示例如下:
function Parent() {
this.name = 'parent'
}
Parent.prototype.say = function() {
console.log('hello')
}
function Child() {}
Child.prototype = new Parent()
Child.prototype.constructor = Child
let child = new Child()
console.log(child.name) // parent
child.say() // hello
借用构造函数继承
借用构造函数继承指通过 call
或 apply
方法来调用父类构造函数,从而继承父类属性。示例如下:
function Parent() {
this.name = 'parent'
this.play = [1, 2, 3]
}
function Child() {
Parent.call(this)
}
let child1 = new Child()
let child2 = new Child()
child1.play.push(4)
console.log(child1.play) // [1, 2, 3, 4]
console.log(child2.play) // [1, 2, 3]
组合继承
组合继承是综合原型继承和借用构造函数继承的方式。它先通过 call
或 apply
方法继承父类属性,再通过将父类实例作为子类原型的方式来继承方法。示例如下:
function Parent(name) {
this.name = name
this.play = [1, 2, 3]
}
Parent.prototype.sayName = function() {
console.log(this.name)
}
function Child(name, age) {
Parent.call(this, name)
this.age = age
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
let child1 = new Child('kevin', '18')
let child2 = new Child('daisy', '20')
child1.play.push(4)
console.log(child1.play) // [1, 2, 3, 4]
console.log(child2.play) // [1, 2, 3]
child1.sayName() // kevin
child2.sayName() // daisy
寄生组合式继承
寄生组合式继承是组合继承的优化,它通过 Object.create
方法来优化了原型继承的方式,从而减少了调用父类构造函数的次数。示例如下:
function Parent(name) {
this.name = name
this.play = [1, 2, 3]
}
Parent.prototype.sayName = function() {
console.log(this.name)
}
function Child(name, age) {
Parent.call(this, name)
this.age = age
}
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
let child1 = new Child('kevin', '18')
let child2 = new Child('daisy', '20')
child1.play.push(4)
console.log(child1.play) // [1, 2, 3, 4]
console.log(child2.play) // [1, 2, 3]
child1.sayName() // kevin
child2.sayName() // daisy
class继承
class继承是ES6中新增的继承方法,通过 class
和 extends
定义父子类, super
关键字来代替 call
方法实现父类属性的继承。示例如下:
class Parent {
constructor(name) {
this.name = name
this.play = [1, 2, 3]
}
sayName() {
console.log(this.name)
}
}
class Child extends Parent {
constructor(name, age) {
super(name)
this.age = age
}
}
let child1 = new Child('kevin', '18')
let child2 = new Child('daisy', '20')
child1.play.push(4)
console.log(child1.play) // [1, 2, 3, 4]
console.log(child2.play) // [1, 2, 3]
child1.sayName() // kevin
child2.sayName() // daisy
以上就是关于JavaScript 继承的五种方式的详细介绍,在实际应用中可以根据具体情况选择不同的继承方式。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:JavaScript 继承详解(五) - Python技术站