继承是什么?
现实生活中,继承是泛指把前人的作风、文化、知识等接受过来
那在 JavaScript 中,简单来说,就是一个对象拥有另一个对象的属性和方法。
为什么要用继承?
通常在一般的项目里不需要,因为应用简单,但你要用纯 js 做一些复杂的工具或框架系统就要用到了,比如 webgis、或者 js 框架如 jquery、ext 什么的,不然一个几千行代码的框架不用继承得写几万行,甚至还无法维护。
ES5 继承的实现(基于原型链)
// 创建一个 Human 构造函数
function Human(name) {
this.name = name
}
Human.prototype.run = function () {
console.log('I can run')
}
// 创建一个 Man 构造函数
function Man(name) {
Human.call(this, name)
this.gender = '男'
}
Man.prototype.fight = function () {
console.log('I can fight')
}
// 让 Man 的原型对象的 proto 指向 Human 的原型对象
Man.prototype.__proto__ = Human.prototype
// 来 new 一个 Man 实例:
var Tony = new Man('Tony')
console.log(Tony)
本来 Man.prototype.proto 是指向 Object.prototype 的,
但是我们加了一句 Man.prototype.proto = Human.prototype ,
所以现在 Man.prototype.proto 就指向了 Human.prototype 。
ES6 实现继承(class 和 extends):
class Human {
constructor(name) {
this.name = name
}
run() {
console.log('I can run')
}
}
class Man extends Human {
constructor(name) {
super(name)
this.gender = '男'
}
fight(){
console.log('I can fight')
}
}
\\ 同样,再来 new 一个 Man 实例看看:
var Allen = new Man('Allen')
console.log(Allen)