js学习之ES6_call 和 bind

 

 bind 不会调用自己

你要想调用啊,还需要自己写个(),就可以啦!!!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script type="text/javascript">
       // jQuery -》bind =》绑定事件 addEvent
       // ES6 bind =》 call
       // eg
       function show(){
           // 问 : 这个this 是谁
           // 答 : window 对象
           console.log(this);
       }
       function show1(x,y){
           
           console.log(this,x,y);
       }

       // this 是 window
       console.log("this 是 window");
       show``;
       // 不传参数 ,this 是 window
       console.log("不传参数 ,this 是 window");
       show.call();
       // 传1个参数 ,this 是 1
       console.log("传1个参数 ,this 是 1");
       show.call(1);
       // 传多个参数 ,this 是 1
       // 2,3 却是show的形参
       console.log("传多个参数 ,this 是 1");
       console.log("2,3 却是show的形参");
       show1.call(1,2,3);

       // => 
       // alert的this本身就是window
       // 第二个参数,那个1是alert的形参
       // 所以运行结果为弹出框 弹出来一个1
       alert.call(this,1);

       // =>
       // let index = 0;

        setTimeout.call(window,()=>{
                //alert.call(window,index);
                alert.call(window,1);
                // index++;
        },3e0);

        // bind
        // 就是一个函数没有运行的状态
        // 运行结果 都就是函数本身
        function showbind(){
            alert(1);
        }
        console.log("showbind 本身啊!!!");
        console.log(showbind);
        
        console.log("showbind 的bind啊!!!");
        console.log(showbind.bind(2));

        // 关于bind的调用问题
        // 与call的区别 
        // 只是调用方式的不同
        function showbind1(x,y,z){
            //alert(1);
            console.log(this,x,y,z);
        }
        showbind1.bind(1,2,3,4)();


        // 晕 这个 我还不太理解
        function showbind2(x,y,z){
            //alert(1);
            console.log(this,x,y,z);
        }
        showbind2.bind(1,2)(5);
        showbind2.bind(1)(5);
    </script>
</body>
</html>

运行结果

 

发布了64 篇原创文章 · 获赞 7 · 访问量 6685

猜你喜欢

转载自blog.csdn.net/MENGCHIXIANZI/article/details/105399289