Search code examples
javascriptfunctionbindingthisbind

Does the func bike () at the top has been overriden by another function at the bottom


var bike = function() {
  console.log(this.name);
}
var name = "Ninja";
var obj1 = { name: "Pulsar" };
var obj2 = { name: "Gixxer" };

var originalBikeFun = bike;
bike = function() {
  originalBikeFun.call(obj1);
};

bike();           // "Pulsar"
bike.call(obj2);  // "Pulsar"

I need explanation because I cant get it. Does the function at the top (which is bike) get overridden when I assigned originalBikeFun at her. How does that work? (Btw, I copy the examples provided by mdn only) #javascript


Solution

  • Let me explain step by step what in your fragment of code going on:

    1. You declare variable bike and assign to it reference to this function:
    function() {
      console.log(this.name);
    }
    
    1. You declare variable originalBikeFun and assign reference to function mentoined above. At this moment you have two variables bike and originalBikeFun that points to just one area in memory where your function stored.
    2. You assign (dereferencing) to bike variable this new function:
    function() {
      originalBikeFun.call(obj1);
    }
    

    At this moment you have variable bike pointed to this function:

    function() {
      originalBikeFun.call(obj1);
    }
    

    and variable originalBikeFun pointed to previously assigned function:

    function() {
      console.log(this.name);
    }
    
    1. When you call to bike function these lines of code executes:
    a) originalBikeFun.call(obj1);
    b) console.log(this.name);
    

    So the result of this call is "Pulsar".

    1. When you call to bike.call(obj2) the difference between previous function call is you just pass obj2 as this pointer, but because in function bike you have only one call with reassign this pointer, so there is no difference.