一种更通用的extend
方法,可以扩展任何方法,而不仅仅是 init:
住在JSBin
function Klass(name){
this.name = name;
this.staticMethod = function(){console.log('static method at Klass');};
}
Klass.prototype.someMethod = function(){console.log('Klass.someMethod');};
Klass.extend = function(extention){
function extendMethod(method1, method2){
var args = arguments;
var contex = this;
return function(){
method1.apply(contex, args);
method2.apply(contex, args);
};
}
var proto = new Klass();
var Extended = function(){Klass.apply(this, arguments);};
for(var key in extention){
if(typeof proto[key] === 'function' && typeof extention[key] === 'function'){
var oldMethod = proto[key];
proto[key] = extendMethod(oldMethod, extention[key]);
}
}
Extended.prototype = proto;
return Extended;
};
var ExKlass = Klass.extend({
someMethod: function(){
console.log('ExKlass.someMethod');
}
});
var k = new Klass();
var ek = new ExKlass();
k.someMethod();
ek.someMethod();