var obj = { a: 1 }
var a = 2
function log(name) {
console.log(`${name} is ${this.a} age`)
}
log('lyq') // lyq is 2 age
log.call(obj, 'lyq') // lyq is 1 age
Function.prototype.myCall = function(context, ...args) {
let ctx = context || window;
let func = Symbol()
ctx[func] = this;
let result = args.length > 0 ? ctx[func](...args) : ctx[func]();
delete ctx[func]
return result
}
log.myCall(obj, 'lyq') // lyq is 1 age
手写javascript系列之手写call
于 2022-03-10 21:54:16 首次发布