JS 中的继承是什么?
两次的原型搜索就是继承。
数组 a 从 Array 中原型搜索到 toString 属性,只是实例属性;a 从 Array 中原型搜索到 (Array 从 Object 中原型搜索到的)valueOf 属性,可以称为继承。
让我们用代码来实现继承:
1. 使用 prototype 实现继承
prototype 的作用:为构造函数内添加实例对象之间的共有属性
// 构造一个 人类
function Human(name){
this.name = name
}
// 给所有 人类 添加一个 跑 的共有属性
Human.prototype.run = function(){
console.log("我叫"+this.name+",我在跑")
return undefined
}
// 构造一个 男人类
function Man(name){
Human.call(this, name)
this.gender = '男'
}
// 所有 男人 都有好战属性
Man.prototype.fight = function(){
console.log('糊你熊脸')
}
2. ES6 实现继承
上面代码的 ES6 版本
// ES6 写法
class Human{
constructor(name){
this.name = name
}
run(){
console.log("我叫"+this.name+",我在跑")
return undefined
}
}
class Man extends Human{ // extends 实现上述继承过程
constructor(name){
super(name) // 调用构造函数:'超类'
this.gender = '男'
}
fight(){
console.log('糊你熊脸')
}
}
总结
JS 继承的原型写法相对 ES6 的写法看上去似乎更复杂,但是事实上更好理解;class 的写法更符合面向对象编程的思维,由于是语法糖因而自然写法简便,但其有一定局限性。