In JavaScript, to create an object, we use 'function' as a constructor; this constructor of a function basically returns an object. when you declare a variable with "var" moments "this.var name", in this case you are trying to use this variable to create an object. This variable declared with "var" is a local variable inside the function.
on the other hand, when you use "this.variableName", you create a property for the object that the constructor function is trying to create.
'this is'. refer to the object that the constructor function creates. "var variableName" is only a local variable and 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');
will create this object:
t{ name:'farhad', age:28, address:'address' }
and
function student2(param1,param2,param3){ var name=param1; var age=param2; var address=param3; } var t2=new student2('farhad',28,'address');
will create this object:
t2{ }
in 't2' you don't see any property
source share