Created
February 25, 2019 07:22
-
-
Save taikulawo/341d21b5597d4096bd527f39b2f0bd0c to your computer and use it in GitHub Desktop.
js bind implements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let b = Function.prototype.bind | |
Function.prototype.bind = Function.prototype.bind || function bind(ctx) { | |
let that = this | |
let slice = Array.prototype.slice | |
let bindArgs = slice.call(arguments,1) | |
// bind可以传递参数,返回的被绑定的函数同样可以传参,所以这里先保存第一次bind的参数,忽略ctx,从 index 1 开始 | |
// 后面将调用时的参数传递进去,concat成一个array | |
return function b(args) { | |
// slice.call 将 arguments 转换为 Array | |
that.apply(ctx,bindArgs.concat(slice.call(arguments))) | |
// From https://stackoverflow.com/a/960870/7529562 | |
//NOTE: The slice function is intentionally generic; it does not require that its this value be an Array object. | |
//Therefore it can be transferred to other kinds of objects for use as a method. | |
// Whether the slice function can be applied successfully to a host object is implementation-dependent. | |
//Therefore, slice works on anything that has a length property, which arguments conveniently does. | |
} | |
} | |
function test (a,b) { | |
console.log(arguments) | |
} | |
let obj = { | |
name: "wwc" | |
} | |
let newtest = test.bind(obj,'1','2') | |
newtest('3','4') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment