// 思路,可以模仿这样调用
// var foo = {
// value: 1,
// bar: function() {
// console.log(this.value)
// }
// };
// foo.bar();
// 所以我们模拟的步骤可以分为:
// 1. 将函数设为对象的属性 (foo.fn = bar)
// 2. 执行该函数 (foo.fn())
// 3. 删除该函数 (delete foo.fn)
// 模拟call
var foo = {
value: 'foo object'
}
function bar (...rest) {
console.log(this.value, ...rest)
}
Function.prototype.mycall = function (context) {
// 不传即为window
let ctx = context || window
// 谁调用 call 方法谁就是 this
ctx.fn = this
let args = []
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i])
}
let res = ctx.fn(...args)
delete ctx.fn
return res
}
bar.mycall(foo, 1, 2)
console