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>

運行結果

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章