JavaScript/call bind apply:修订间差异
来自康健生活
创建页面,内容为“== 引言 == == call == === 上下文 === === 继承 ===” |
|||
| (未显示同一用户的1个中间版本) | |||
| 第3行: | 第3行: | ||
=== 上下文 === | === 上下文 === | ||
=== 继承 === | === 继承 === | ||
== bind == | |||
=== bind 实现 === | |||
<syntaxhighlight lang="javascript"> | |||
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同时将调用时传递的序列和预置序列进行合并 | |||
} | |||
}</syntaxhighlight> | |||
或者 | |||
<syntaxhighlight lang="javascript"> | |||
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)</syntaxhighlight> | |||