日期:2014-05-16  浏览次数:20439 次

一个javascript继承的基础类Base.js

一个javascript继承的基础类Base.js

官网:http://dean.edwards.name

http://dean.edwards.name/weblog/2006/03/base/

一个javascript继承的基础类
首先我是一个面向对象的程序员,并且javascript支持prototype 方式继承,例如:

function Animal(name) {};
Animal.prototype.eat = function() {};
Animal.prototype.say = function(message) {};
?我想要一个更漂亮的基类,来实现javascript的面相对象.

1.我想不用prototype并容易地创建类.
2.我想用一个方法重写父类方法,就像java支持的那样.
3.在原型阶段我想要避免调用一个类的构造函数函数.
4.我想在类上容易的创建静态方法或属性.
5.我想实现上述功能不用全局函数
6.我想实现上诉功能不影响Object.prototype

/*
    Base.js, version 1.1a
    Copyright 2006-2010, Dean Edwards
    License: http://www.opensource.org/licenses/mit-license.php
*/

var Base = function() {
    // dummy
};

Base.extend = function(_instance, _static) { // subclass
    var extend = Base.prototype.extend;
    
    // build the prototype
    Base._prototyping = true;
    var proto = new this;
    extend.call(proto, _instance);
  proto.base = function() {
    // call this method from any other method to invoke that method's ancestor
  };
    delete Base._prototyping;
    
    // create the wrapper for the constructor function
    //var constructor = proto.constructor.valueOf(); //-dean
    var constructor = proto.constructor;
    var klass = proto.constructor = function() {
        if (!Base._prototyping) {
            if (this._constructing || this.constructor == klass) { // instantiation
                this._constructing = true;
                constructor.apply(this, arguments);
                delete this._constructing;
            } else if (arguments[0] != null) { // casting
                return (arguments[0].extend || extend).call(arguments[0], proto);
            }
        }
    };
    
    // build the class interface
    klass.ancestor = this;
    klass.extend = this.extend;
    klass.forEach = this.forEach;
    klass.implement = this.implement;
    klass.prototype = proto;
    klass.toString = this.toString;
    klass.valueOf = function(type) {
        //return (type == "object") ? klass : constructor; //-dean
        return (type == "object") ? klass : constructor.valueOf();
    };
    extend.call(klass, _static);
    // class initialisation
    if (typeof klass.init == "function") klass.init();
    return klass;
};

Base.prototype = {    
    extend: function(source, value) {
        if (arguments.length > 1) { // extending with a nam