call、apply和bind实现

时间:2019-09-29
本文章向大家介绍call、apply和bind实现,主要包括call、apply和bind实现使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

call、apply和bind实现

实现call和apply
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

Function.prototype.call = function(obj) {
let context = obj || window; //当context为null时指向window
// 首先要获取调用call的函数,this指向调用call的执行函数
context.fn = this;
let args = [];
// args为 ["arguments[1]", "arguments[2]", "arguments[3]"]
for (let i = 1; i < arguments.length; i++) {
args.push("arguments[" + i + "]");
}
//eval(string) 可计算某个字符串,并执行其中的的 JavaScript 代码
//这里 args 会自动调用 Array.toString() 这个方法
//需要将每个参数传递给context.fn()
let result = eval("context.fn(" + args + ")");
delete context.fn;
return result;
};

Function.prototype.apply = function(obj, arr) {
let context = obj || window;
context.fn = this;
let result;
if (!arr) {
result = context.fn();
} else {
let args = [];
for (let i = 0, len = arr.length; i < len; i++) {
args.push("arr[" + i + "]");
}
result = eval("context.fn(" + args + ")");
}
delete context.fn;
return result;
};
实现bind

bind() 方法会创建一个新函数,当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this之后的一序列参数将会在传递的实参前传入作为它的参数。
bind 还有一个特点,就是一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function.prototype.bind = function(context) {
//调用 bind 的不是函数报错
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

let self = this;
let args = Array.prototype.slice.call(arguments, 1);

let fNOP = function() {
};

let fBound = function() {
let bindArgs = Array.prototype.slice.call(arguments);
// 当作为构造函数时,this 指向实例,此时结果为 true,将绑定函数的 this 指向该实例,可以让实例获得来自绑定函数的值
// 当作为普通函数时,this 指向 window,此时结果为 false,将绑定函数的 this 指向 context
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
};

fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};

原文:大专栏  call、apply和bind实现


原文地址:https://www.cnblogs.com/chinatrump/p/11606613.html