Skip to content

Instantly share code, notes, and snippets.

@mumoshu
Created December 30, 2010 08:18
Show Gist options
  • Save mumoshu/759586 to your computer and use it in GitHub Desktop.
Save mumoshu/759586 to your computer and use it in GitHub Desktop.
var Fuga = function() {
this.hoge = 'hoge';
};
Fuga.prototype = {
fizz: function() {
console.log(this.hoge);
},
buzz: function(x) {
console.log(this.hoge + ':' + x);
},
bindToBuzz: function(x) {
var self = this;
// closureにselfとxを入れるでゲソ
return function() {
return self.buzz(x);
};
},
loopset: function() {
setInterval($.proxy(this.fizz, this), 1000);
// this.buzz(' :-)')でbuzzが実行されてしまうのでNG
// - $.proxyの第一引数には関数を渡さなければならない
// - setIntervalの第一引数にも関数を渡さなければならない
// - $.proxy(a,b)は,bをthisにbindしてa()を呼び出す関数を返す
// setInterval($.proxy(this.buzz(' :-)'), this), 1000);
setInterval(this.bindToBuzz(' :-D'), 1000);
// closureその1
setInterval((function(self, x){
return function() {
return self.buzz(x);
};
})(this, " :-P"), 1000);
// closureその2
// この書き方の方がわかりやすいし、よく見るかなぁ
var self = this;
var x = " :-I"
setInterval(function() {
return self.buzz(x);
}, 1000);
}
}
var x = new Fuga();
x.loopset();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment