var obj = { a: 1 }
var a = 2
function log(name) {
console.log(`${name} is ${this.a} age`)
}
log('lyq') // lyq is 2 age
log.apply(obj, ['lyq']) // lyq is 1 age
Function.prototype.myApply = 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.myApply(obj, ['lyq'])
手写javascript系列之手写apply
于 2022-03-10 21:59:26 首次发布