JavaScript 深入之 call 和 apply 的模拟实现

JavaScript 深入之 call 和 apply 的模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 第一版
Function.prototype.call2 = function(context) {
// 首先要获取调用call的函数,用this可以获取
// this的指向为bar,因为bar是Funciton的实例
context.fn = this;
context.fn();
// 相当于把bar挂载到foo上,所以bar可以取到value
delete context.fn;
}

// 测试一下
var foo = {
value: 1
};

function bar() {
console.log(this.value);
}

bar.call2(foo); // 1

但是第一版不可以传递多个参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 第二版
Function.prototype.call2 = function(context) {
context.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
eval('context.fn(' + args +')');
//这里 args 会自动调用 Array.toString() 这个方法。
//这里eval函数输出的是:context.fn(arguments[1],arguments[2])
delete context.fn;
}

// 测试一下
var foo = {
value: 1
};

function bar(name, age) {
console.log(name)
console.log(age)
console.log(this.value);
}

bar.call2(foo, 'kevin', 18);
// kevin
// 18
// 1

第二版的问题是,1.this 参数可以传 null,当为 null 的时候,视为指向 window2.函数是可以有返回值的!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 第三版
Function.prototype.call2 = function (context) {
var context = context || window;
context.fn = this;

var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}

var result = eval('context.fn(' + args +')');
delete context.fn
return result;
}

// 测试一下
var value = 2;

var obj = {
value: 1
}

function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}

bar.call2(null); // 2

console.log(bar.call2(obj, 'kevin', 18));
// 1
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }

es6 版

1
2
3
4
5
6
7
Function.prototype.call2 = function (context, ...args) {
context = context || window
context.__fn__ = this
let result = context.__fn__(...args)
delete context.__fn__
return result
}

apply 的实现跟 call 类似,在这里直接给代码,代码来自于知乎 @郑航的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function.prototype.apply = function (context, arr) {
var context = Object(context) || window;
context.fn = this;

var result;
if (!arr) {
result = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
}

delete context.fn
return result;
}

文章参考来源:https://github.com/mqyqingfeng/Blog/issues/11