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
Programming is a way to express things so that computers and humans can understand them.
Is it still good practice to use it when calling functions?
There is no exact answer. Both of your snippets do work. So the computer is able to understand it. However the second one is maybe confusing for humans (aka your coworkers):
this.someFunc();
What should this
refer to? Yes technically it refers to window
, but from a human point of view it is unclear.
Thats why i would definetly not refer to this
in this case. However there are other good usecases for it:
function changeColor(){
//When just looking here it makes no sense to refer to this
this.color = "green";
}
const car = { color: "grey" };
//But now it makes sense as `this` refers to the `car` it is called on
car.changeColor = changeColor;
TLDR: Use this
to refer to methods/properties, and leave it away when refering to pure functions and variables.
For a starting JS developer it might be easiest to get concept of This by using it in an event listener callback. I. e., "click" event binds This to object which is the target (Like "look, i clicked on THIS!").
<ul class="dynamic-list" id="myList">
<li class="dynamic-list__item">Item 1</li>
<li class="dynamic-list__item">Item 2</li>
<li class="dynamic-list__item">Item 3</li>
</ul>
<script type="text/javascript">
let listItems = document.getElementById("myList").childNodes;
[...listItems].forEach(function(item) {
item.addEventListener("click", removeListItem, false);
})
// Callback for event, using THIS
function removeListItem() {
// Log the text content of <li> to the console. Which one? THIS one.
console.log(this.textContent);
// Get the parent of what? Of THIS! And remove its child. Which one? THIS one!
this.parentNode.removeChild(this);
}
</script>
Of course Rajeshs answer is much, much more complex, but I hope THIS can be also helpful…
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.'This' is used inside a function and it contains the value of the object that invokes the function.
For example:
function a(){
this.newVariable = 'Phil';
}
a();
console.log(newVariable); //This line would display Phil
In this case, even though we just define newVariable inside the function a(). The object that invokes the function is the global object window, so 'this' points to window and this.newVariable is at the global scope.
Another example would be:
var c={
log:function(){
this.name = 'Phil';
}
}
In this case, 'this' points to the object c, since the log function will be invoked by c.
We have more tricky cases in the use of the object 'this' in Javascript. This is a good article to grasp the concept: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/