Javascript call() & apply() vs bind()?

后端 未结 22 1918
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

22条回答
  •  北海茫月
    2020-11-22 03:33

    It allows to set the value for this independent of how the function is called. This is very useful when working with callbacks:

      function sayHello(){
        alert(this.message);
      }
    
      var obj = {
         message : "hello"
      };
      setTimeout(sayHello.bind(obj), 1000);
    

    To achieve the same result with call would look like this:

      function sayHello(){
        alert(this.message);
      }
    
      var obj = {
         message : "hello"
      };
      setTimeout(function(){sayHello.call(obj)}, 1000);
    

提交回复
热议问题