Search code examples
javascriptthis

Why use apply() or call() when you can pass the target object as a parameter?


I understand the use cases for using apply() and call(). You can essentially call a function from another object, and specify the this binding. This of course, only make sense if said function uses the this keyword.

What I don't understand, is, why would you create a function inside an object, and then decide that you want to reuse it somewhere else by changing this? To me it sounds like the function made sense in the first object, and rather than refactoring the function to live on its own, the programmer decided to just leave it there and call it with apply/call.

It would make more sense to me to take that function out of that object, and put it somewhere else where it's clearly visible that it can be used by different objects, by having it take that target object as an explicit parameter.

Am I missing something?


Solution

  • I can give you one example where this is useful. Long time ago before ES6, to achieve javascript inheritance was a bit more complicated - there were two types of inheritance. So in order to create one class and inherit it with another class you had to do something like this:

    function Parent(){
       this.parentParam="parentParam";
    };
    
    Parent.prototype.logThisContext = function(){ 
       console.log(this);
    };
    
    function Child(){
       Parent.call(this);
    };
    
    Child.prototype = Object.create(Parent.prototype);
    

    Now if you want to override parent logThisContext function, you should write this:

    Child.prototype.logThisContext = function(){
       // calling base functionality
       Parent.prototype.logThisContext.call(this);
       // add child functionality
       console.log("overriden behavior");
    }
    

    If you do not call logThisContext with this, you will log the prototype itself instead of the concrete instance.

    You can play with that code removing the calling of this and you will see the difference by yourself :)

    EDIT: I am not sure if this gives you the answer you want, but logThisContext is technically a function inside object as you mentioned in your answer.