手写 实现bind()

逐步实现js的bind方法

  1. 原函数无参数版 bind
  2. 原函数带参数版 bind
  3. 区分原函数是否作为构造函数
一. 原函数无参数版 bind
  1. 原函数作为新_context对象内的属性,在对象中调用,即可使用_context的作用域
  2. 根据 bind 要求返回闭包
  1. 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;
    	}
    }
    
  2. 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时指定,也可能在调用绑定新作用域后的新函数中指定,也可能都有。

  1. bind 中接收参数,并在闭包中于闭包参数合并为完整参数,再一起提供给新函数。
  2. ES6之前没有解构语法,使用 恶魔方法 eval 进行函数调用
  1. ES6之前

    Function.prototype.myBind =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值