【JS中bind函数详解,实例代码分析】

JS中bind函数详解

------------------------------分割线-------------------------------------
这是我第一次写这种类型博客,记录一下~
DATE:2022.1.16

关于bind()函数,首先从英文的意思入手,bind有绑定的意思。

函数的引用:
假设已经存在一个函数fn
var new_fn = fn.bind( 要绑定的对象, 参数1, 参数2, … );
oWrap.onclick = fn.bind( 要绑定的对象, 参数1, 参数2, … );

首先这个函数执行的时候有以下步骤:

步骤:
1.构造一个和原函数内容块一样的函数 。
2.将原函数的this赋值给新构造的函数的this 。
3.构造的函数第一个传入的参数再次对这个新函数的this赋值(要有实际意义的值才能改变,如undefined,null等等是不可以进行赋值的,一个标签对象、数组、字符串、数字(包括整形和浮点型)都是可以对新函数的this进行赋值) 。
4.将这个新构造的函数返回return 。

对这个第三点比较重要,这边再细细的细分一下

  • 当第一个参数为 this, undefined, null不会改变原函数this的指向,原函数的this指向window,新函数也指向window
  • 当第一个参数为 字符串、数字(浮点型和整形)、数组、标签对线等等,this会指向这个第一个参数,与其绑定。

------------------------------分割线-------------------------------------

以下是bind函数的代码实例:

1. 与元素this指向相同
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style>
    	/* wrap的样式 */
        #wrap {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
	<!-- 一个wrap对象 -->
    <div id="wrap"></div>

    <script>
        wrap.onclick = fn.bind( this , 1 , 2 , 3 ); 
        //bind中的this是fn的this,this改成undefined和null效果一样
        function fn( a , b ,c ){
            console.log( a , b ,c );
            console.log( this );
        }

        window.fn();

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

对于这段代码,其实没有任何意义,新构造的函数指向与原函数相同的this,在这里也就是指向window对象。

2. 改变新函数的this指向,将其指向wrab对象
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <style>
    	/* 样式 */
        #wrap {
            width: 100px;
            height: 100px;
            background-color: red;
            line-height: 100px;
            text-align: center;
        }
        #wrab {
            width: 100px;
            height: 100px;
            background-color: skyblue;
            line-height: 100px;
            text-align: center;
        }
    </style>
</head>
<body>
    <!-- 标签对象 -->
    <div id="wrap"></div>
    <div id="wrab"></div>

    <script>
        wrap.onclick = fn.bind( wrab , 1 , 2 , 3 ); 
        //将wrap的this指向wrab标签,通过点击改变其背景颜色
        function fn( a , b ,c ){
            console.log( a , b ,c );
            console.log( this );
            this.style.backgroundColor = "green";
        }

    </script>
</body>
</html>
  • 原图片
    在这里插入图片描述
  • 点击wrap后,wrab改变
    在这里插入图片描述
    到这里,差不多已经对bind函数了解lo~~,
    标注:上述写的步骤是本人一步步测试出来的,没有非常权威,若想追求真理,可以去官网文档查看~
    这边可以参考一下MDN文档:

链接: Function.prototype.bind() - JavaScript | MDN.

最后祝大家一起努力,共同进步哦!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值