1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

関数にsetTimeout機能を追加する

Posted at

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も同じ形で可能

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?