zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Prototype的Class.create函数解析

函数 解析 create Class prototype
2023-06-13 09:14:30 时间
复制代码代码如下:

/**
*一个设计精巧的定时执行器
*首先由Class.create()创建一个PeriodicalExecuter类型,
*然后用对象直接量的语法形式设置原型。
*
*需要特别说明的是rgisterCallback方法,它调用上面定义的函数原型方法bind,并传递自己为参数。
*之所以这样做,是因为setTimeout默认总以window对象为当前对象,也就是说,如果registerCallback方法定义如下的话:
*registerCallback:function(){
*setTimeout(this.onTimerEvent,this.frequency*1000);
*}
*那么,this.onTimeoutEvent方法执行失败,因为它无法访问this.currentlyExecuting属性。
*而使用了bind以后,该方法才能正确的找到this,也就是PeriodicalExecuter的当前实例。
*/
varPeriodicalExecuter=Class.create();
PeriodicalExecuter.prototype={
initialize:function(callback,frequency){
this.callback=callback;
this.frequency=frequency;
this.currentlyExecuting=false;

this.registerCallback();
},

registerCallback:function(){
setTimeout(this.onTimerEvent.bind(this),this.frequency*1000);
},

onTimerEvent:function(){
if(!this.currentlyExecuting){
try{
this.currentlyExecuting=true;
this.callback();
}finally{
this.currentlyExecuting=false;
}
}

this.registerCallback();
}
}

具体Class.create()背后做了什么,具体来看看Class的实现。
复制代码代码如下:


/**
*创建一种类型,注意其属性create是一个方法,返回一个构造函数。
*一般使用如下
*varX=Class.create();返回一个类型,类似于java的一个Class实例。
*要使用X类型,需继续用newX()来获取一个实例,如同java的Class.newInstance()方法。
*
*返回的构造函数会执行名为initialize的方法,initialize是Ruby对象的构造器方法名字。
*此时initialize方法还没有定义,其后的代码中创建新类型时会建立相应的同名方法。
*/
varClass={
create:function(){
returnfunction(){
this.initialize.apply(this,arguments);
}
}
}

Class.create实际上是返回一个函数,那么new的时候,做了些什么呢。参照MDN

Whenthecodenewfoo(...)isexecuted,thefollowingthingshappen:

Anewobjectiscreated,inheritingfromfoo.prototype.
Theconstructorfunctionfooiscalledwiththespecifiedargumentsandthisboundtothenewlycreatedobject.newfooisequivalenttonewfoo(),i.e.ifnoargumentlistisspecified,fooiscalledwithoutarguments.
Theobjectreturnedbytheconstructorfunctionbecomestheresultofthewholenewexpression.Iftheconstructorfunctiondoesn"texplicitlyreturnanobject,theobjectcreatedinstep1isusedinstead.(Normallyconstructorsdon"treturnavalue,buttheycanchoosetodosoiftheywanttooverridethenormalobjectcreationprocess.)
new的时候会执行该返回的函数,即执行this.initialize.apply(this,arguments);此时的this就是新生成的对象,这也就是说了所有对象的初始化工作全部委托给initialize函数了。

-------

这里为什么要把自己的initialize方法绑定到自己身上??