简单实现了个JavaScript类继承(比下午在公司实现的要简单得多),继承prototype方法和静态方法,实际使用过程中mix函数还需要丰满一下。这东西水很深,自己也一知半解的,不多说直接放代码。
Function.prototype.method = function(name,fn){ this.prototype[name] = fn; return this; } Function.method('inherits',(function(){ function mix(a,b){ for(var i in b){ //replace if(typeof a[i] == 'undefined'){ a[i] = b[i]; } } } return function(Parent){ var fn = function(){}; mix(this.prototype,Parent.prototype); mix(this,Parent); this.__super__ = Parent; //static method //object.__super__.demo //prototype method //object.__super__.prototype.hidden return this; }; })()); var a = function(){}; var b = function(){}; var c = function(){}; var d = function(){}; a.prototype.show = function(){ console.log('a show'); }; b.prototype.hidden = function(){ console.log('b hidden'); }; a.test = function(){ console.log('a test'); }; b.demo = function(){ console.log('b demo'); }; //usage b.inherits(a); c.inherits(a); d.inherits(b); |
-EOF-