I want to create an object. And, in almost code I have read, they often use this style:
function student(_id, _name, _year){
this.id = _id;
this.name = _name;
this.year = _year;
}
But, I don’t know what the difference with below code :
function student (_id, _name, _year){
var id = _id;
var name = _name;
var year = _year;
}
I have tested for example, alert properties to screen, and see no difference.
Thanks 🙂
When you declare variables using var they are only visible in the scope of your function/constructor. They are private so to say.
Using this, in this case, goes hand in hand with a constructor function. When you instantiate a student all the values assigned to this will be publicly accessible.
First I recommend renaming your student into Student with a capital S. This is a convention that indicates it is a constructor and you need to use the new keyword.
If you now instantiate the Student you can access the values…
When using var you can’t…