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
Let me explain step by step what in your fragment of code going on:
bike
and assign to it reference to this function:function() {
console.log(this.name);
}
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.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);
}
bike
function these lines of code executes:a) originalBikeFun.call(obj1);
b) console.log(this.name);
So the result of this call is "Pulsar".
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.