JavaScript 中 apply、call 和 bind 方法的手写实现
JavaScript 中 apply、call 和 bind 方法的手写实现
call 的实现
与 apply 类似,但参数以逗号分隔传递
// 给所有的函数添加一个mycall的方法
Function.prototype.mycall = function (context, ...args) {// 在这里可以去执行调用的那个函数(foo)// 问题: 得可以获取到是哪一个函数执行了mycall// 1.获取需要被执行的函数if (typeof this !== "function") {throw new TypeError("Function.prototype.mycall called on non-function");}// 2.对context转成对象类型(防止它传入的是非对象类型)context =context !== null && context !== undefined ? Object(context) : window;// 3.创建唯一属性键const fnKey = Symbol("fn");// 4. 将当前函数绑定到 contextcontext[fnKey] = this;// 5.调用需要被执行的函数var result = context[fnKey](...args);// 6. 删除临时属性delete context[fnKey];// 7.将最终的结果返回出去return result;
};
- 测试代码
function foo(a, b, c) {console.log(this, a, b, c);
}
foo.mycall({ name: "zs" }, 1, 2, 3);
foo.mycall(null, 1, 2, 3);
foo.mycall(undefined, 1, 2, 3);
foo.mycall(123, 1, 2, 3);
apply 的实现
立即执行函数,将 this 绑定到指定对象,参数以数组形式传递
// 给所有的函数添加一个myapply的方法
Function.prototype.myapply = function(context, argArray) {// 在这里可以去执行调用的那个函数(foo)if (typeof this !== 'function') {throw new TypeError('Function.prototype.mycall called on non-function');}// 2.对context转成对象类型(防止它传入的是非对象类型)context = (context !== null && context !== undefined) ? Object(context): windowconst fnKey = Symbol('fn')// 将当前函数绑定到 contextcontext[fnKey] = this// 处理参数,当不传入参数,argArray为undefined,...undefined会报错,所以需要处理一下argArray = argArray || []// 3.调用需要被执行的函数var result = context[fnKey](...argArray)delete context[fnKey]// 4.将最终的结果返回出去return result
}
- 测试代码
function foo(a, b, c) {console.log(this, a, b, c);
}
foo.myapply({ name: "zs" }, [1, 2, 3]);
bind 的实现
返回新函数,永久绑定 this 和预设参数
Function.prototype.mybind = function(context, ...argArray) {// 1.获取到真实需要调用的函数if (typeof this !== "function") throw new TypeError("必须是函数");const fn = this// 2.绑定thiscontext = (context !== null && context !== undefined) ? Object(context): windowconst fnKey = Symbol('fn')function newFn(...args) {// 3.将函数放到context中进行调用context[fnKey] = fn// 特殊: 对两个传入的参数进行合并var finalArgs = [...argArray, ...args]var result = context[fnKey](...finalArgs)delete context[fnKey]// 4.返回结果return result}return newFn
}
- 测试代码
function foo() {console.log("foo被执行", this)return 20
}function sum(num1, num2, num3, num4) {console.log(num1, num2, num3, num4)console.log(this)
}