ES 5 写法
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 = '男'
}
let x = function(){}
x.prototype = Human.prototype
Man.prototype = new x()
Man.prototype.fight = function(){
console.log('打架')
}
以上代码意思是:
- 首先声明一个Human的函数,接受一个传参等于当前的name,然后在Human的原型上声明一个run函数。
- 再声明一个Man函数,基本属性gender为男,通过call传递this上下文到Human函数动态取名字。
- 通过Man.prototype = new xx() 将Human绑定到Man的prototype上。
- 我们可以创造一个新对象 let xx = new Man('阿嚏') ,即变量 xx 对象拥有属性:{name:'阿嚏',gender:‘男’},xx 其prototype继承自Human,xx.prototype === Human(),即xx.__proto__ === Human(),又等于xx.__proto__.__proto__ === Human().prototype。
补充:
实际上下面这段代码的意思就是将Human.prototype绑定到Man的prototype.__proto__上,Man即继承了Human。
Man.prototype.__proto__ = Human.prototype
因为IE浏览器不支持直接改动对象的__proto__属性,因此好的兼容办法可以用 new 构造一个新对象,强行指定新对象的prototype。
let x = function(){}
x.prototype = Human.prototype
Man.prototype = new x()
ES 6 写法
class Human{
constructor(name) {
this.name = name
}
run() {
console.log('我的名字是'+this.name+',我在奔跑')
return undefined
}
}
class Man extends Human{
constructor(name){
super(name)
this.gender = '男'
}
fight() {
console.log('打架')
}
}
事实上我们用浏览器控制台打出以上代码,得到的结果与ES5一致,都是通过js的原型链来达到继承的目的。ES6的继承语法就是语法糖,看起来与java一样,但实际内部实现却与java不同。
上面super(name)的super,在面向对象术语中管它叫超类,其实可以简单理解为父类,继承自他的爸爸Human。