前言
bind,call,apply三者共同点是都可以改变函数的执行上下文,区别在于bind会返回一个新的函数,而call和apply不会返回的新的函数,而是立即执行函数。
正文
call的代码实现
Function.prototype.call = function (context) {
context = context || window
context.fn = this
//let argus = [...arguments].slice(1)
//let result = context.fn(...argus)
let argus = []
for(var i=1, var len=arguments.length; i<len; i++){
argus.push('arguments['+i+']')
}
let result = eval('context.fn('+argus+')')
delete context.fn
return result
}
apply的代码实现
Function.prototype.apply = function (context, array) {
context = context ? Object(context) : window
context.fn = this
let result
if (!array) {
result = context.fn()
} else {
result = context.fn(...array)
}
delete context.fn
return result
}
bind的代码实现
Function.prototype.bind = function (context) {
if (typeof this !== 'function') {
throw new Error('please use bind by function!')
}
let self = this
let argus1 = [...arguments].slice(1)
let fb = function () {}
function fBind () {
let argus2 = [...arguments]
return self.apply(this instanceof fb ? this : context, [...argus1, ...argus2])
}
fb.prototype = this.prototype
fBind.prototype = new fb()
return fBind
}
网友评论