Im curious when it is needed/best practice to use the keyword this
. I understand that this
is used when determining a functions this
value but is it always needed?
The reason I am asking is because I have a internal function and it is called within my module and all it really does is sort some data you pass it. My question is should I call this function using the this
keyword or stand alone.
E.g:
function formatSomeData(data){
//code........
}
this.formatSomeData(data);
OR
formatSomeData(data);
I get that the context of where the function is being called and what its purpose is matters in answering the question, but in this case like I mentioned, I really don't need to access the this
object at any point. Is it still good practice to use it when calling functions?
What I'm asking is not so much as to how "this" works, but when is it appropriate to use it and when isn't it.
when it is needed/best practice to use the keyword this
This is usually used when you want to access something in some. So for instance, if you have a custom object and want to use some property inside some method, you should use this
.
function Person(fname, lname){
this.fname = fname;
this.lname = lname;
this.fullName = function(){
return this.fname + ' ' + this.lname;
}
}
var p = new Person('foo', 'bar');
console.log(p.fullName())
If you see, in current constructor, I created a function(fullName
) which needs to access fname
and lname
properties of the object it is part of. This is a place this
must be used.
Now while declaration, when to use
this
?
Any property in a constructor that is a part of this
will be a part of the object. So if you need something that is only accessible to you but not outside, you can use function
instead of this
.
function Person(fname, lname){
var self = this;
self.fname = fname;
self.lname = lname;
// This function is private
function getFullName() {
var name = '';
var seperator = '';
if (fname) {
name += self.fname;
seperator = ' ';
}
if (lname) {
name += seperator + self.lname;
}
return name;
}
this.fullName = function(){
return getFullName();
}
}
var p = new Person('foo', 'bar');
console.log(p.fullName())
As for your code, I have already explained in comment why it works:
In non-strict mode,
this
will point towindow
and any declaration not in a function will be a part of global scope.
But as rightly pointer by @Jonas W its a bad practice. Why it is bad?
var|let|const
) will become part of global scope.