gstackoverflow gstackoverflow - 11 days ago 5
Javascript Question

difference between functionName() and functionName.call(this)

I research functional inheritance in javascript.
According the article I have read I have wrote the code:

function Base(){
var enableVar = true

this.enable = function(){
console.log("enable");
enableVar = true;
}
this.disable = function(){
console.log("disable");
enableVar = true;
}
}

function Child(){
Base.call(this);
}

new Child().enable();


this code works properly and I see message in console.

but I don't understand row:

Base.call(this);


for me it is
Base
function invocation with
this
replaced with
this
thus it is same with
Base();


But looks like my state is wrong. I see error:

VM898:62Uncaught TypeError: (intermediate value).enable is not a function(…)


Please clarify difference for me.

Answer

functionName.call(obj) calls functionName normally, with one main difference: Inside of functionName, this refers to obj. Normally this refers to window, but making this reference obj is very good for inheritance because you can just keep on using this throughout all of your constructors.