Tell me which one to use, which are used in good programming practice. I write in javascript but I usually use one and the other in the same code ... Eae?
The difference is in the instances you create from this "class" . The instance only exposes what is in this
of it or has been inherited :
var objeto = new Func();
objeto.fn_this(); // "this"
objeto.fn_func(); // ERRO - objeto.fn_func is not a function
objeto.fn_var(); // ERRO - objeto.fn_var is not a function
So basically you should put in this
what you want it to be exposed (but often better put in the prototype). The other two forms you use for what is "private", which can only be accessed at scope of the builder.
It's worth to also understand The difference between function fn(){}
and var fn = function(){}
, and still why fn_func
and fn_var
can be called from within fn_this
. See also: What is e How does the Javascript context work?
The this
operator will always get the parent operator. If the parent is not defined by default it will be the window
object.
The var
, as the name already indicates, is a variable. However, it can receive objects and functions.
When you declare a function in Javascript, you can do it normally with function
or use var fn = function() {}
. In this way we say that the fn variable receives a function, and to be able to use it it would be fn();
.
When it is inside an object, the reference will be to the object itself, however we have to be careful about the scope. If it is in a function the reference will be the function. So you can find by then codes using var self = this;
for the reference still to continue in the class.