实现思路:
ES5写法
Function.prototype._call = function (context) {if (typeof this !== 'function') {console.error('type error');return false}context = context || window// 获取传入的参数let args = [...arguments].slice(1)// 将调用的函数设为对象的方法context.fn = this// 调用函数result = context.fn(...args)// 将属性删除delete context.fnreturn result}function fn() {this.a = arguments[0]}let obj = {name: 'zs'}fn._call(obj, 'ls')
ES6写法
Function.prototype._call = function (context, ...args) {if (typeof this !== "function") {throw new TypeError('Error')}// 判断是否传入context参数,如果没有传入则设置为默认值windowcontext = context || window// 创建一个唯一的属性const key = Symbol()// 将当前的this绑定到创建的属性上context[key] = thisresult = context[key](...args)delete context[key]return result}function fn() {this.a = arguments[0]}let obj = {name: 'zs'}fn._call(obj, 'ls')
