@@ -39,12 +39,28 @@ bindFoo(); // 1
39
39
Function .prototype .bind2 = function (context ) {
40
40
var self = this ;
41
41
return function () {
42
- self .apply (context);
42
+ return self .apply (context);
43
43
}
44
44
45
45
}
46
46
```
47
47
48
+ 此外,之所以 ` return self.apply(context) ` ,是考虑到绑定函数可能是有返回值的,依然是这个例子:
49
+
50
+ ``` js
51
+ var foo = {
52
+ value: 1
53
+ };
54
+
55
+ function bar () {
56
+ return this .value ;
57
+ }
58
+
59
+ var bindFoo = bar .bind (foo);
60
+
61
+ console .log (bindFoo ()); // 1
62
+ ```
63
+
48
64
## 传参的模拟实现
49
65
50
66
接下来看第二点,可以传入参数。这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?我在执行 bind 返回的函数的时候,可不可以传参呢?让我们看个例子:
@@ -83,7 +99,7 @@ Function.prototype.bind2 = function (context) {
83
99
return function () {
84
100
// 这个时候的arguments是指bind返回的函数传入的参数
85
101
var bindArgs = Array .prototype .slice .call (arguments );
86
- self .apply (context, args .concat (bindArgs));
102
+ return self .apply (context, args .concat (bindArgs));
87
103
}
88
104
89
105
}
@@ -142,7 +158,7 @@ Function.prototype.bind2 = function (context) {
142
158
// 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
143
159
// 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
144
160
// 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
145
- self .apply (this instanceof fBound ? this : context, args .concat (bindArgs));
161
+ return self .apply (this instanceof fBound ? this : context, args .concat (bindArgs));
146
162
}
147
163
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
148
164
fBound .prototype = this .prototype ;
@@ -168,7 +184,7 @@ Function.prototype.bind2 = function (context) {
168
184
169
185
var fBound = function () {
170
186
var bindArgs = Array .prototype .slice .call (arguments );
171
- self .apply (this instanceof fNOP ? this : context, args .concat (bindArgs));
187
+ return self .apply (this instanceof fNOP ? this : context, args .concat (bindArgs));
172
188
}
173
189
174
190
fNOP .prototype = this .prototype ;
@@ -255,7 +271,7 @@ Function.prototype.bind2 = function (context) {
255
271
256
272
var fBound = function () {
257
273
var bindArgs = Array .prototype .slice .call (arguments );
258
- self .apply (this instanceof fNOP ? this : context, args .concat (bindArgs));
274
+ return self .apply (this instanceof fNOP ? this : context, args .concat (bindArgs));
259
275
}
260
276
261
277
fNOP .prototype = this .prototype ;
0 commit comments