关于js的call、apply、bind,并重写
let obj1 = {
name: '123',
getName: function () {
return this.name
}
}
let obj2 = {
name: '456'
}
console.log(obj1.getName()) // 123
console.log(obj1.getName.call(obj2)) // 456
Function.prototype.myCall = function (context = window) {
let args = Array.from(arguments).splice(1)
if (typeof this !== 'function') return
// 关键在于利用对象的特性,直接在将函数指向新的对象,并指向该函数
!context.__fn__ && context.__fn__ = this
let res = context.__fn__(...args)
// 删除该对象上的属性
delete context.__fn__
return res
}
console.log(obj1.getName.myCall(obj2)) // 456
posted on 2021-08-21 14:20 chinesedon007 阅读(36) 评论(0) 收藏 举报
浙公网安备 33010602011771号