逐步实现js的
bind
方法
- 原函数无参数版
bind
- 原函数带参数版
bind
- 区分原函数是否作为构造函数
一. 原函数无参数版 bind
- 原函数作为新_context对象内的属性,在对象中调用,即可使用_context的作用域
- 根据
bind
要求返回闭包
-
ES6之前
Function.prototype.myBind = function(_context){ // _context检测 _context = _context? _context: window; let that = this; // 按要求返回闭包(函数) return function(){ // 函数挂入_context内 _context.__fn = that; // 函数调用 let result = _context.__fn(); // 删除_context内的新函数 delete _context.__fn; return result; } }
-
ES6之后
Function.prototype.myBind = function(_context){ // _context检测 _context = _context? _context: window; // 按要求返回闭包(函数) return () => { // 函数挂入_context内 let fnKey = Symbol(); _context[fnKey] = this; // 函数调用 let result = _context[fnKey](); // 删除_context内的新函数 delete _context[fnKey]; return result; } }
二、原函数带参数版 bind
原函数的参数可能在
bind
时指定,也可能在调用绑定新作用域后的新函数中指定,也可能都有。
- 在
bind
中接收参数,并在闭包中于闭包参数合并为完整参数,再一起提供给新函数。- ES6之前没有解构语法,使用 恶魔方法
eval
进行函数调用
-
ES6之前
Function.prototype.myBind =