call、apply、bind模拟实现

call 方法模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
Function.prototype.call = function(context, ...args) {
var context;
try {
context = context || window;
} catch (e) {
context = global;
}
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};

apply 方法模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
Function.prototype.apply = function(context, args) {
var context;
try {
context = context || window;
} catch (e) {
context = global;
}
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};

bind 方法模拟实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (typeof Function.prototype.bind !== 'function') {
Function.prototype.bind = function(context, ...rest) {
if (typeof this !== 'function') {
throw new TypeError('invalid invoked!');
}
let self = this;
return function F(...args) {
if (this instanceof F) {
return new self(...rest, ...args);
}
return self.apply(context, rest.concat(args));
};
};
}
你的支持将鼓励我继续创作!