代码复用模式
谈及代码复用,首先想到的是代码的继承性(inheritance)。
类式继承
默认继承
//
function Parent(name) {
this.name = name || "helen"
}
//
Parent.prototype.say = function() {
return this.name;
}
//
function Child() {}
//
inherit(Child,Parent)
function inherit(C,P) {
C.prototype = new P();
}
var kid = new Child();
kid.say();
追溯原型链
借用构造函数
function Parent(name) {
this.name = name||'alice';
}
Parent.prototype.say = function() {
return this.name;
}
function Child(name){
Parent.apply(this,arguments)
}
var kid = new Child(‘abc');
kid.name //
优缺点:
无法从原型中继承任何东西,不会为每个实例重新创建原型
可以获得父对象的真实副本,也不会存在子对象意外覆盖父对象属性的风险
借用和设置原型
先借用构造函数,再设置子构造函数的原型使其指向一个构造函数创建的新实例
function Parent(name) {
this.name = name || "helen"
}
//
Parent.prototype.say = function() {
return this.name;
}
//
function Child(name) {
Parent.apply(this,arguments)
}
Child.prototype = new Parent();
var kid = new Child('alice')
kid.name // alice
kid.say() // alice
delete kid name
kid.say() // helen
共享原型
function inherit(C,P){
C.prototype = P.prototype;
}
原型继承(现代继承)
无类的存在
var parent = {
name:'alice'
}
var child = object(parent)
function object(o){
function F() {}
F.prototype = o
return new F()
}