functionのprototypeを使ってコーディングしているときに、定義したfunctionのprototypeメンバとして登録した関数をsetTimeoutしたときに、関数内でthisが元の定義したfunctionになるようにする方法
Function.prototype.doTimeout = function (duration, self, args){
var func = this;
return setTimeout(
function() {
func.apply(self, args);
},
duration);
};
Functionにこんな関数を定義しておくと、以下のような使い方ができる
function NewClass(){
this.prop = 666;
};
NewClass.prototype.do_after_timeout = function(arg){
alert(arg + ':' + this.prop);
};
NewClass.prototype.disp = function(){
this.do_after_timeout.doTimeout(3000, this, ['this.prop']);
};
var nf = new NewClass();
nf.disp();
scriptタグ内にこれを埋めれば3秒後に「this.prop:666」というメッセージがアラートに表示される。
setIntervalも同じ形で可能