象使用java类一样使用javscript类,javascript 类机制实现源码

1象使用java类一样使用javscript类,javascript类机制实现源码

习惯了使用java,转入到javascript后,一直苦恼为什么不能象java那样建立类及其对象呢。

尝试了很多方式,最近在网上看到一段代码,才发现原来在js中可以如此简单高效的实行类机制。

也打消了我对javascript类机制会特别消耗性能的顾虑,让我放心的使用javascript类机制。

代码比较短,只用了js的基本特性。参考价值比较高,在这里show一下代码。

实现类机制代码如下:

javascript代码

(function(){

varinitializing=false,fnTest=/xyz/.test(function(){xyz;})?/\b_super\b/:/.*/;

//ThebaseClassimplementation(doesnothing)

this.Class=function(){};

//CreateanewClassthatinheritsfromthisclass

Class.extend=function(prop){

var_super=this.prototype;

//Instantiateabaseclass(butonlycreatetheinstance,

//don'truntheinitconstructor)

initializing=true;

varprototype=newthis();

initializing=false;

//Copythepropertiesoverontothenewprototype

for(varnameinprop){

//Checkifwe'reoverwritinganexistingfunction

prototype[name]=typeofprop[name]=="function"&&

typeof_super[name]=="function"&&fnTest.test(prop[name])?

(function(name,fn){

returnfunction(){

vartmp=this._super;

//Addanew._super()methodthatisthesamemethod

//butonthesuper-class

this._super=_super[name];

//Themethodonlyneedtobeboundtemporarily,sowe

//removeitwhenwe'redoneexecuting

varret=fn.apply(this,arguments);

this._super=tmp;

returnret;

};

})(name,prop[name]):

prop[name];

}

//Thedummyclassconstructor

functionClass(){

//Allconstructionisactuallydoneintheinitmethod

if(!initializing&&this.init)

this.init.apply(this,arguments);

}

//Populateourconstructedprototypeobject

Class.prototype=prototype;

//Enforcetheconstructortobewhatweexpect

Class.prototype.constructor=Class;

//Andmakethisclassextendable

Class.extend=arguments.callee;

returnClass;

};

})();

测试代码如下:

javascript代码

varPerson=Class.extend({

init:function(isDancing){

this.dancing=isDancing;

},

dance:function(){

returnthis.dancing;

}

});

varNinja=Person.extend({

init:function(){

this._super(false);

},

dance:function(){

//Calltheinheritedversionofdance()

returnthis._super();

},

swingSword:function(){

returntrue;

}

});

varp=newPerson(true);

p.dance();//=>true

varn=newNinja();

n.dance();//=>false

n.swingSword();//=>true

//Shouldallbetrue

pinstanceofPerson&&pinstanceofClass&&

ninstanceofNinja&&ninstanceofPerson&&ninstanceofClass

相关推荐