bind函数的实现

文章详细解释了JavaScript中bind方法的实现原理,通过保存函数上下文、参数并创建一个新的函数来确保调用时的this值。示例展示了如何使用bind方法绑定对象和参数,并在之后的调用中正确打印出预期结果。
摘要由CSDN通过智能技术生成
Function.prototype.bind = function(){
	let self = this,	//保存当前函数
	    context = [].shift.call(arguments),	//保存当前上下文
	    args = [].slice.call(arguments);	// 保存参数
	
	return function(){
		self.apply(context, [].concat.call(args, [].slice.call(arguments)))
	}
}


    let obj = {
      name: 'xx'
    }
    var fun = function(a,b,c, d){
      console.log(this.name, 'name');
      console.log(a,b,c,d);
    }.bind(obj, 3,4);

    fun(5,6)

在这里插入图片描述

参考资料:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <link rel="icon" href="./vue.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>xx管理系统</title>
</head>
<body>
  <div id="app"></div>
  <!-- <script type="module" src="/src/main.js"></script> -->

  <script>


    Function.prototype.bind = function(){
      let self = this,
          context = [].shift.call(arguments),
          args = [].slice.call(arguments)

          return function(){

            console.log([].concat.apply(arg, [].slice.call(arguments)),   1111111);
            console.log([].concat.call(arg, [].slice.call(arguments)),   2222);
            self.apply(context, [].concat.call(args, [].slice.call(arguments)))
          }
          
      console.log(11111111);
    }

    let obj = {
      name: 'xx'
    }
    var fun = function(a,b,c, d){
      console.log(this.name, 'name');
      console.log(a,b,c,d);
    }.bind(obj, 3,4);

    fun(5,6)



    function ab(a, b, c) {
      console.log(a,b,c);
      console.log(arguments, 99999);

      let xx = [].shift.call(arguments)
      console.log(xx, 'xx');
    }


    ab(1,2,3);

    console.log(ab.length, 66);

  </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值