1.原型继承
如何让一个对象继承另一个对象?
function Language(name){
this.name = name
this.score = 8.0
}
Language.prototype.popular = function () {
return this.score/10*100 + '%'
}
function FastLanguage() {
this.speed = '0.01'
}
FastLanguage是Language的子类,如何让FastLanguage拥有Language的属性呢?
由继承规则可知,需要让FastLanguage的原型指向Language的原型,即:
new FastLanguage()---->FastLanguage.prototype---->Language.prototype---->Object.prototype---->null
如何让FastLanguage的原型指向Language的原型呢?
需要借助一个中间对象Temp,让FastLanguage.prototype指向新的Temp对象,Temp的原型指向Language的原型即可。
function Language(name){
this.name = name
this.score = 8.0
}
Language.prototype.popular = function () {
return this.score/10*100 + '%'
}
function FastLanguage(name) {
// this表示FastLanguage对象,绑定this.name的值
Language.call(this,name)
this.speed = '0.01'
}
function F() {
}
F.prototype = Language.prototype
FastLanguage.prototype = new F()
// 需要将FastLanguage原型对应的constructor恢复为以前
FastLanguage.prototype.constructor = FastLanguage
fastLanguage = new FastLanguage('C')
console.log(fastLanguage.popular())
运行结果: 80%
2.原型继承小结
1)使用call调用父类构造函数,绑定到当前对象的属性值
2)使用中间对象Temp实现原型链的继承