不久前在写笔记的小JOE页的博客上看到一篇名为《自创js类与继承的实现》的文章,最近自己狠劲折腾js便想起了这篇文章,于是我结合着QQ地图里的代码,简单的也写了一个JS类继承的实现,代码如下:

    function extend(destination, source) {
    var value = null;
    var property = null;
    if (destination && source) {
    for (property in source) {
    value = source[property];
    if (value !== undefined) {
    destination[property] = (typeof(value) == 'object' && !(value.nodeType) && !(value instanceof Array)) ? extend({}, value) : value;
    }
    }
    if (source.hasOwnProperty && source.hasOwnProperty('toString')) {
    destination.toString = source.toString;
    }
    }
    return destination;
    }

    Class = function() {
    var _C = function() {
    if (this.initialize) {
    this.initialize.apply(this, arguments);
    }
    };
    var extended = {};
    var parent;
    for (var i = 0; i < arguments.length; ++i) {
    if (typeof arguments[i] == 'function') {
    parent = arguments[i].prototype;
    } else {
    parent = arguments[i];
    }
    extend(extended, parent);
    }

    _C.prototype = extended;

    _C.extend = function(args){
    return Class(this,args);
    };

    return _C;
    }

    //定义父类
    var Parent=Class({
    p:1,
    initialize:function(){
    this.p=4;
    alert(this.p);
    }
    });
    //定义子类1
    var Son=Parent.extend({//继承Parent类
    s:2,
    initialize:function(str2){
    alert(this.s);
    }
    });
    //定义子类2
    var Son2=Son.extend({
    s2:3,
    initialize:function(str3){
    alert(this.s);
    }
    });

    var p=new Parent('a');
    console.log(p);
    var s=new Son('b');
    console.log(s);
    var s2=new Son2('b3');
    console.log(s2);

《全文完》