Skip to content

Commit 3290b02

Browse files
committed
修订JavaScript深入之bind的模拟实现
1 parent 3622374 commit 3290b02

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

articles/深入系列文章/JavaScript深入之bind的模拟实现.md

+21-5
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,28 @@ bindFoo(); // 1
3939
Function.prototype.bind2 = function (context) {
4040
var self = this;
4141
return function () {
42-
self.apply(context);
42+
return self.apply(context);
4343
}
4444

4545
}
4646
```
4747

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+
4864
## 传参的模拟实现
4965

5066
接下来看第二点,可以传入参数。这个就有点让人费解了,我在 bind 的时候,是否可以传参呢?我在执行 bind 返回的函数的时候,可不可以传参呢?让我们看个例子:
@@ -83,7 +99,7 @@ Function.prototype.bind2 = function (context) {
8399
return function () {
84100
// 这个时候的arguments是指bind返回的函数传入的参数
85101
var bindArgs = Array.prototype.slice.call(arguments);
86-
self.apply(context, args.concat(bindArgs));
102+
return self.apply(context, args.concat(bindArgs));
87103
}
88104

89105
}
@@ -142,7 +158,7 @@ Function.prototype.bind2 = function (context) {
142158
// 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
143159
// 以上面的是 demo 为例,如果改成 `this instanceof fBound ? null : context`,实例只是一个空对象,将 null 改成 this ,实例会具有 habit 属性
144160
// 当作为普通函数时,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));
146162
}
147163
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
148164
fBound.prototype = this.prototype;
@@ -168,7 +184,7 @@ Function.prototype.bind2 = function (context) {
168184

169185
var fBound = function () {
170186
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));
172188
}
173189

174190
fNOP.prototype = this.prototype;
@@ -255,7 +271,7 @@ Function.prototype.bind2 = function (context) {
255271

256272
var fBound = function () {
257273
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));
259275
}
260276

261277
fNOP.prototype = this.prototype;

0 commit comments

Comments
 (0)