I have js object like this:
var Dog = function(dogName) {
this.bark = function() {
console.log(dogName + " is barking");
}
}
and
var Dog = function(dogName) {
this.dogName = dogName;
this.bark = function() {
console.log(this.dogName + " is barking");
}
}
I can use both the same way:
var puppy = new Dog("Ringo");
puppy.bark();
My question is is there any practical difference between those two approaches? Is it better to assign constructor parameters to this.<field>, or I can just utilize those parameters straight away as they are accessible to inner functions? Are there any special cases for both?
The difference is what happens when you say
With the first approach, it will still use the name “Ringo” and with the second approach it will say “George”. For the same reason if you try to say
that will work with the second version but not the first. So if your goal is to make
dogNameeffectively private so that it can’t be accessed or changed after being initialized, you should go with the first approach, otherwise always go with the second approach.