Hello I’m a newcomerin JavaScript language.
I started to see some examples of JavaScript code.
and i cant understand the following code segment:
function Employee(name,salary)
{
this.name=name;
this.salary=salary;
this.paycheck=function()
{
var monthly=this.salary/12;
document.write(this.name+ ": " +monthly);
};
}
var emp= new Employee("Fred",10000);
emp.paycheck();
My question: what is the meaning of word this near the property inside class (i.e. ,this.name=name; this.salary=salary; )?
Thank you in advance!
The use of
thiscould be explained as meaning “properties that apply to this instance”. SinceEmployeeis a constructor function (you create instances of it using thenewoperator), every instance has its own values for those properties:Note that this also means every instance of
Employeehas its own copy of thepaycheckmethod. This is not particularly efficient, as a separate copy of the function has to be stored in memory for every instance of the object. You could instead declare the method on theprototypeof theEmployeeobject, which would mean the method would be shared between all instances.