Created
December 30, 2010 08:18
-
-
Save mumoshu/759586 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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