Last active
July 26, 2018 09:30
-
-
Save Caldis/2ec20c775c5e24b1322571d33e94707e to your computer and use it in GitHub Desktop.
实现一个 Bind 函数
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
Function.prototype.b = function(env, arg) { | |
// 从 arg 中去掉 evn, 取出 bind 的附加参数 | |
// arguments 为非典型数组, 没有 slice 方法, 需要这样调用来裁剪并转换为数组 | |
const arg = Array.prototype.slice.call(arguments, 1) | |
// 保存当前的上下文 | |
const context = this | |
// 返回 bind 后的函数 | |
const func = function(bindArg) { | |
// 接收到 bind 后的函数调用后, 先拼接新的参数到原先的 bind 的附加参数后面 | |
// Array.prototype.slice.call(bindArg) 可将 bindArg 转换为数组并拼接 | |
arg = arg.concat(Array.prototype.slice.call(bindArg)) | |
context.apply(env, arg) | |
} | |
// 寄生组合继承, 只调用一次superType构造函数,并且避免了在 subType.prototype 上创建不必要的属性 | |
// 1. 新建一个空的构造函数 | |
function Super() {} | |
// 2. 令这个构造函数的原型等于父类的原型 | |
Super.prototype = context.prototype | |
// 3. 使用这个构造函数创建新的对象, 这个对象则拥有了父类的原型 | |
const superPrototype = new Super() | |
// 4. 将这个对象的原型给到目标函数, 完成继承 | |
func.prototype = superPrototype | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment