var obj = { a: 1 }
var a = 2
function log(name) {
console.log(`${name} is ${this.a} age`)
}
log('lyq') // lyq is 2 age
let m = log.bind(obj, 'lyq')
m() // lyq is 1 age
Function.prototype.myBind = function (context, ...args) {
let fn = this;
args = args ? args : []
return function newFn(...newFnArgs) {
if (this instanceof newFn) {
return fn(...args, ...newFnArgs)
}
return fn.apply(context, [...args, ...newFnArgs])
}
}
let res = log.myBind(obj, 'lyq')
res() // lyq is 1 age
手写javascript系列之手写bind
最新推荐文章于 2024-05-30 11:27:58 发布