I am really struggling to understand how does this works in constructor function for object creation in Javascript environment.
below is the code snippet:
function Employee() {
basicSalary = 12000;
overtime = 10;
rate = 200;
this.getWage = function () {
return basicSalary+(overtime*rate);
}
}
let emp = new Employee();
console.log(emp.basicSalary);//undefined
console.log(emp.getWage());//14000
in above code I am getting undefined for basicSalary variable. So in order to get basicSalary value I prefix it with this inside function like:
this.basicSalary = 12000;
But, in doing so I am getting error in accessing getWage() method. It says:
Uncaught ReferenceError: basicSalary is not defined
at Employee.getWage (index.js:6)
at index.js:11
However, if I prefix this to the basicSalary in returning statement inside getWage() function, I am able to access both basicSalary variable and getWage() method.
Also If I replace all my code to factory function i.e. Object literal type like here:
function employee(){
return {
basicSalary : 12000,
overtime : 10,
rate : 200,
getWage:function(){
return this.basicSalary+(this.overtime*this.rate); // accessing values through `this`
}
};
}
const e2 = employee();
console.log(e2.basicSalary);
console.log(e2.getWage());
Now I am easily able to get both basicSalary and getWage() method. Only thing that I needed to do was put this in return statement inside getWage() method.
in both these approaches this works differently. I am confused. Please share some knowledge on how to use this in Javascript.
thisworks differently ” Why do you think that? What do you perceive as different? The biggest difference betweenbasicSalary = ...andthis.basicSalary = ...is that the first creates a variable and the second creates an object property. You cannot refer to an object property as if it was a variable (your first attempt to fix it). The last example is almost the same as the previous one, except you are creating the object explicitly vs havingnewcreate it for you.