What is the difference between this and var within a Javascript class?

Asked

Viewed 222 times

1

Código com as três dúvidas

tell me which one to use, which ones are used in good programming practices. I write in javascript but I usually use one and the other in the same code... Eae?

  • @rubStackOverflow The context of that question is different, it’s about when to use var versus omit the var.

2 answers

4


The difference is in the instances you create of this "class". The instance only exposes what is in this her 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 exposed (but often it’s better to put in the prototype). The other two forms you use for what is "private", which can only be accessed on scope of the builder.

Also worth understanding the difference between function fn(){} and var fn = function(){}, and yet why fn_func and fn_var can be called from within fn_this. See also: What is and how the context works in Javascript?

1

The operator this will always catch the parent operator. If the parent is not set by default it will be the object window.

The var, as its name already indicates, it is a variable. However it can receive objects and functions.

When you declare a Javascript function, you can do it normally with the function or use the var fn = function() {}. In this way we say that the variable fn receives a function, and to be able to use it would be fn();.

When it is inside an object, the reference will be to the object itself, but we have to be careful with the scope. If it is in a function the reference will be the function. So you can find there codes using the var self = this; for the reference still remain in the class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.