- 将函数设为对象的属性
- 执行&删除这个函数
- 指定this到函数并传入给定参数执行函数
- 如果不传入参数,默认指向window
/** * 实现一个call方法 */ Function.prototype.myCall = function (context) { context = context ? Object(context) : window; context.fn = this; // 获取调用call的函数 let args = []; for (let i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); } let result = context.fn(...args); return result; } var value = 'global'; var foo = { value: 1 }; var bar = function (name, age) { console.log(this.value); return { value: this.value, name, age } }; bar.myCall(null); console.log(bar.myCall(foo, '铁拐李', 18));