JavaScript/call bind apply
来自康健生活
引言
call
上下文
继承
bind
bind 实现
Function.prototype.bind = function(newThis) {
var aArgs = Array.prototype.slice.call(arguments, 1) //拿到除了newThis之外的预置参数序列
var that = this
return function() {
return that.apply(newThis, aArgs.concat(Array.prototype.slice.call(arguments)))
//绑定this同时将调用时传递的序列和预置序列进行合并
}
}
或者
var obj = {
color: 'green'
}
function demo () {
console.log(arguments)
console.log(this.color)
}
/*
* bind1 模拟bind方法
* @fn 需要执行的函数
* @obj 传入的作用域
*/
var bind1 = function (fn, obj){
//取从索引值为2开始的后边的所有参数,生成数组
var paramArr = [].slice.call(arguments,2);
return function(){
//拼接两次传入的除了fn和作用域之后的参数
fn.apply(obj, paramArr.concat([].slice.call(arguments,0)))
}
}
var curFn = bind1(demo, obj, 3,3,3)
curFn(4,4,4)
No categories