bind()方法
- bind()方法有两个参数。第一个参数调用绑定函数时作为 this 参数传递给目标函数的值,第二个参数当目标函数被调用时,被预置入绑定函数的参数列表中的参数
- 例如:
function fn(a, b, c) {
return a + b + c;
}
var _fn = fn.bind(null, 10);
var ans = _fn(20, 30);
Function.prototype.myBind = function (that, ...args) {
const funcThis = this;
return function (..._args) {
return funcThis.apply(that, args.concat(_args));
}
}
apply()方法
Function.prototype.myApply = function (context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
context = context || window;
context.fn = this;
let result;
if (arguments[1]) {
result = context.fn;
} else {
result = context.fn();
}
delete context.fn;
return result;
}