When it comes to creating objects in JavaScript, we typically use the 'function' keyword as a constructor. These constructor functions are responsible for returning an object. If you declare a variable using 'var' instead of 'this.varName', it means you are attempting to use those variables to create an object. Variables declared with 'var' are simply local variables within the function scope.
On the other hand, when you use 'this.variableName', you are actually creating a property for the object that the constructor function is trying to instantiate.
'this.' refers to the object being created by the constructor function.
'var variableName' declares a local variable that is not a property of the 'this' object.
function student(param1, param2, param3) {
this.name = param1;
this.age = param2;
this.address = param3;
}
var t = new student('farhad', 28, 'address');
This will create the following object:
t{
name: 'farhad',
age: 28,
address: 'address'
}
However, if we look at the following example:
function student2(param1, param2, param3) {
var name = param1;
var age = param2;
var address = param3;
}
var t2 = new student2('farhad', 28, 'address');
We'll see that the object 't2' does not contain any properties.