0
What are uses of "this" keyword in javascript? When to use it?
I have 2 code for sum two number, those resulting same. In code 1 i have used this keyword and in code 2 i have not used this keyword. Both giving correct and same result. So 1.what are uses of this keyword? When to use this? 2.What are the Importance of "this" keyword? Code link : https://code.sololearn.com/WbskpUWmDWtW/?ref=app https://code.sololearn.com/WbskpUWmDWtW/?ref=app
3 Answers
+ 2
Try this instead to see the difference:
objbox = {
a: 5,
b: 5,
sum: 0,
sum1: function() {
this.sum = this.a + this.b;
console.log(this.sum)
},
sum2: function(a, b) {
sum = a + b;
console.log(sum)
}
}
objbox.sum1()
objbox.sum2(3, 3)
sum = 0
console.log(objbox.sum)
console.log(sum)
+ 10
"this" is a reference to the current object, but its value depends on where exactly it's used. It can be quite tricky (as most things in javascript, they start stinking when you scratch the surface...)
The full story:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
The short and beginner friendly version:
https://www.w3schools.com/js/js_this.asp
+ 6
In your particular code:
this.sum = this.a + this.b;
and
this.sum = a + b;
These lines get the same result because you previously assigned
this.a = a
and
this.b = b
You should understand, that "this.a" is a field that belongs to the function object, and "a" is an input variable. So they could have even different values inside the function. In this code there is no difference.