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的指向,并返回新的函数。
<!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>

猜你喜欢

转载自www.cnblogs.com/allen2333/p/9198940.html