实现JavaScript类继承(inherits)

2012-03-23 07:45

实现JavaScript类继承(inherits)

by 枯藤昏鸦

at 2012-03-22 23:45:57

original http://ioio.name/javascript-inherits.html

简单实现了个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-


Related posts:


Copyright © 2005~2011 | Permalink | 0 Comments | Close To U

订阅 Twitter 域名优惠码 Media Temple空间 主机/域名优惠码 )