JavaScript - call() , apply() and bind()

參考

  1. https://www.codementor.io/niladrisekhardutta/how-to-call-apply-and-bind-in-javascript-8i1jca6jp
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

區別

  1. Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.(改變this指向)
  2. call/apply方法的區別只是第二個參數的不一樣。
  3. You can use call()/apply() to invoke the function immediately.(call()和apply()當即執行,沒有返回東西)
  4. bind()返回一個新的函數(相對於複製了一樣的函數,this指向指定的對象,返回綁定後的函數。)注意,f1.bind(obj,...)後,obj.f1並不存在,因此只是改變了函數this的指向,並返回新的函數。

例子1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script>
    
    function foo(x,y) {
      console.log((x+y)+this);
    }

    var obj = {
      age:10,
      sayHi:function () {
        console.log("年齡是:"+this.age);
      }
    };

    var f1 = foo.bind(obj, 100, 200);
    f1();  // bind複製函數後,綁定到對象,而後返回新的綁定後的函數
    obj.f1(); // Uncaught TypeError: obj.f1 is not a function , bind只是返回一個函數,改變了函數裏的this指向,並無在obj中添加函數f1
    // bind什麼均可,由於改變的是this的指向,看下面的兩個bind
    // f1.bind('1',100,200)
    // f1.bind(1,100,200)

    var f2 = foo.call(obj, 100, 200);
    f2();  // Uncaught TypeError, 由於call沒有返回值


    var f3 = foo.apply(obj, [100, 200]);
    f3();  // Uncaught TypeError, 由於apply沒有返回值
    
   
    

  </script>
</head>
<body>


</body>
</html>

例子2

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script>

    //構造函數
    function F1() {
      // 一個隨機數
      this.number=Math.ceil(Math.random()*10)+1;
    }


    //原型中添加了一個方法
    F1.prototype.show1=function () {
      //this---->實例對象
      window.setTimeout(this.show2.bind(this),1000);
      // 由於 var f = this.show2只是一個function,f.bind(this)就將this指向了F1的實例對象。否則沒有bind的話,f傳進去window.setTimeout,this指向window。
    };
    //原型中添加了一個方法
    F1.prototype.show2=function () {
      //this---->實例對象
      //輸出了本身產生的隨機數
      console.log(this.number+"產生了一個數字");
    };
    var f1=new F1();
    f1.show1();
  </script>
</head>
<body>


</body>
</html>
相關文章
相關標籤/搜索