View difference between Paste ID: icDeqQWD and cTzFVtrW
SHOW: | | - or go back to the newest paste.
1
/*--------------------------------------------------*/
2
/* Original Example */
3
4
Obj = {
5
  myalert: function(){
6
    alert("bam!");
7
  },
8
  callbackFn: function(){
9
    this.myalert();
10
  },
11
  firstFn: function(callback, callbackObj){
12
    callback.apply(callbackObj);
13
  },
14
  secondFn: function(){
15
    this.firstFn(this.callbackFn, this);
16
  }
17
}
18
Obj.secondFn();
19
20
/* Example using closure to store function context */
21
Obj = {
22
  myalert: function(){
23
    alert("bam!");
24
  },
25
  callbackFn: function(){
26
    this.myalert();
27
  },
28
  firstFn: function(callback){
29-
  	callback();
29+
    callback();
30
  },
31
  secondFn: function(){
32-
  	var that = this;
32+
    var that = this;
33-
  	var closure = function() {
33+
    var closure = function() {
34-
		that.callbackFn.apply(that, arguments);
34+
        that.callbackFn.apply(that, arguments);
35-
	};
35+
    };
36
37
    this.firstFn(closure);
38
  }
39
}
40
Obj.secondFn();
41
42
/*--------------------------------------------------*/
43
/* Example generalizing the closure to bind a function to a context */
44
45
var bindThis = function(callback, context) {
46-
	return function() {
46+
    return function() {
47-
		callback.apply(context, arguments);
47+
        callback.apply(context, arguments);
48-
	};
48+
    };
49
};
50
51
Obj = {
52
  myalert: function(){
53
    alert("bam!");
54
  },
55
  callbackFn: function(){
56
    this.myalert();
57
  },
58
  firstFn: function(callback){
59-
  	callback();
59+
    callback();
60
  },
61
  secondFn: function(){
62-
  	// using custom bind function that we wrote (see above) 
62+
    // using custom bind function that we wrote (see above) 
63
    this.firstFn(bindThis(this.callbackFn, this));
64
65-
	// or using jQuery's proxy function to do the same thing
65+
    // or using jQuery's proxy function to do the same thing
66-
	this.firstFn($.proxy(this.callbackFn, this));
66+
    this.firstFn($.proxy(this.callbackFn, this));
67
68-
	// or using underscore/lodash's bind function
68+
    // or using underscore/lodash's bind function
69-
	this.firstFn(_.bind(this.callbackFn, this));
69+
    this.firstFn(_.bind(this.callbackFn, this));
70
  }
71
}
72
Obj.secondFn();