Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*--------------------------------------------------*/
- /* Original Example */
- Obj = {
- myalert: function(){
- alert("bam!");
- },
- callbackFn: function(){
- this.myalert();
- },
- firstFn: function(callback, callbackObj){
- callback.apply(callbackObj);
- },
- secondFn: function(){
- this.firstFn(this.callbackFn, this);
- }
- }
- Obj.secondFn();
- /* Example using closure to store function context */
- Obj = {
- myalert: function(){
- alert("bam!");
- },
- callbackFn: function(){
- this.myalert();
- },
- firstFn: function(callback){
- callback();
- },
- secondFn: function(){
- var that = this;
- var closure = function() {
- that.callbackFn.apply(that, arguments);
- };
- this.firstFn(closure);
- }
- }
- Obj.secondFn();
- /*--------------------------------------------------*/
- /* Example generalizing the closure to bind a function to a context */
- var bindThis = function(callback, context) {
- return function() {
- callback.apply(context, arguments);
- };
- };
- Obj = {
- myalert: function(){
- alert("bam!");
- },
- callbackFn: function(){
- this.myalert();
- },
- firstFn: function(callback){
- callback();
- },
- secondFn: function(){
- // using custom bind function that we wrote (see above)
- this.firstFn(bindThis(this.callbackFn, this));
- // or using jQuery's proxy function to do the same thing
- this.firstFn($.proxy(this.callbackFn, this));
- // or using underscore/lodash's bind function
- this.firstFn(_.bind(this.callbackFn, this));
- }
- }
- Obj.secondFn();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement