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

后端 未结 22 2275
醉话见心
醉话见心 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:32

    bind function should be use when we want to assign a function with particular context for eg.

    var demo = {
               getValue : function(){ 
                 console.log('demo object get value       function') 
                }
               setValue : function(){  
                  setTimeout(this.getValue.bind(this),1000)           
               }
     }
    

    in above example if we call demo.setValue() function and pass this.getValue function directly then it doesn't call demo.setValue function directly because this in setTimeout refers to window object so we need to pass demo object context to this.getValue function using bind. it means we only passing function with the context of demo object not actully calling function.

    Hope u understand .

    for more information please refer javascript bind function know in detail

提交回复
热议问题