@@ -70,4 +70,70 @@ Using a closure to access inner and outer object instances simultaneously
70
70
71
71
This mechanism can be particularly useful when dealing with callbacks, though
72
72
in those cases, it is often better to use ` Function.bind ` , which will avoid any
73
- overhead associated with scope traversal.
73
+ overhead associated with scope traversal. In case you haven't used this before, let
74
+ us now explore a brief introduction.
75
+
76
+ ` Function.bind ` is used to create a new function, which when called, itself then
77
+ calls this function in the context of the supplied 'this' value, using a given set
78
+ of arguments which will precede any arguments provided when the new function was
79
+ initially called.
80
+
81
+ As ` bind ` is a recent addition to ECMAScript 5, it may not be present in all browsers,
82
+ which is something to be wary of when deciding whether to use it or not. It is however
83
+ possible to work around support by using the following shim, which whilst a partial
84
+ implementation only, may be sufficient as a temporary bridge until ` bind ` is widely
85
+ adopted according to the specification.
86
+
87
+ <div class =" example " markdown =" 1 " >
88
+ if ( !Function.prototype.bind ) {
89
+ Function.prototype.bind = function( obj ) {
90
+ var slice = [ ] .slice,
91
+ args = slice.call(arguments, 1),
92
+ self = this,
93
+ nop = function () {},
94
+ bound = function () {
95
+ return self.apply( this instanceof nop ? this : ( obj || {} ),
96
+ args.concat( slice.call(arguments) ) );
97
+ };
98
+
99
+ nop.prototype = self.prototype;
100
+ bound.prototype = new nop();
101
+ return bound;
102
+ };
103
+ }
104
+ </div >
105
+
106
+ One of the simplest uses of ` bind ` is making a function, which regardless of how it's
107
+ called, is called with a particular value for ` this ` . A common mistake made is
108
+ attempting to extract a method from an object, then later calling that function and
109
+ expecting it to the use the origin object as it's ` this ` . This however can be solved
110
+ by creating a bound function using the original object as demonstrated below.
111
+
112
+ <div class =" example " markdown =" 1 " >
113
+ //lets manipulate "this" with a basic example
114
+ var user = "johnsmith",
115
+ module = {
116
+ getUser: function(){
117
+ return this.user;
118
+ },
119
+ user: "janedoe"
120
+ };
121
+
122
+ //module.getUser() is called where "module" is "this" and "module.user" is returned.
123
+ module.getUser();
124
+ //janedoe
125
+
126
+ //let's now store a reference in the global version of "this"
127
+ var getUser = module.getUser;
128
+
129
+ //getUser() called, "this" is global, "user" is returned
130
+ getUser();
131
+ //johnsmith
132
+
133
+ //store a ref with "module" bound as "this"
134
+ var boundGetUser = getUser.bind(module);
135
+
136
+ //boundGetUser() called, "module" is "this" again, "module.user" returned.
137
+ boundGetUser();
138
+ //janedoe
139
+ </div >
0 commit comments