javascript prototype 继承
javascript设计模式:继承
function extend(subClass, superClass, methods) {
var F = function(){};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if (superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
for (var p in methods) {
subClass.prototype[p] = methods[p];
}
}
function SP() {
this.cls = 'super class'
}
SP.prototype.print = function() {
console.log(this.cls)
}
function SB() {}
SB.prototype = SP.prototype
SB.prototype.print = function() {
console.log('changed by subclass')
}
// output: changed by subclass
// SB prototype对象的改变同时影响到了SP,也即此时SB和SP是共享同一个prototype对象
// SB.prototype = new SP() 解决
new SP().print()
function SP() {
this.cls = 'super class'
}
SP.prototype.print = function() {
console.log(this.cls)
}
function SB() {}
SB.prototype = new SP()
new SB().print() // super class
// 避免在子类SB中获得在父类SP中定义的属性
function F() {}
F.prototype = SP.prototype
SB.prototype = new F()
new SB().print() // undefined
function People(name) {
this.name = name
}
People.prototype.say = function() {
console.log(this.name)
}
function Baby(name) {
// 借用构造函数
Baby.superclass.constructor.call(this, name)
}
Vanilla.extend(Baby, People)
var baby = new Baby('jj')
console.log(baby)