以下是网上看到的一个例子,感觉对理解JS面向对象的机制非常有用:
function Timer(iInterval){
//if not set the timer interval ,then defalut set to 500ms
this.Interval = iInterval || 500;
this._handleInterval;
this.TimerEvent=null
function Start(){
if(this.Interval!=0){
this._handleInterval=setInterval("TimerCallBack()",this.Interval);
}
}
function Stop(){
clearInterval(this._handleInterval);
}
function TimerCallBack(){
if (typeof this.TimerEvent=="function"){
this.TimerEvent();
}
else if(this.TimerEvent!=null && this.TimerEvent.length>0){ //length 表示形参个数
eval(this.TimerEvent);
}
}
}
//Code for Instance
var t=new Timer(3);
//------------------------------------//
//1.
t.TimerEvent=function(){
//todo
}
//2.
t.TimerEvent="alert(/"hello/")";
//3.
t.TimerEvent=tTimerCall;
//----------------------------------//
t.Start();
t.Stop();
function tTimerCall(){
}