When I try to specify the parameter names when calling a function from inside a JavaScript class constructor, I get a ReferenceError
.
I will show the problem based on a simplified example:
Suppose I have an object and methods like so:
class Person {
constructor(name, age) {
this.name = name,
this.age = age
}
addYear() {
this.age++;
}
changeName(newName) {
this.name = newName;
}
changeAge(newAge) {
this.age = newAge;
}
changeAgeAndName(newName, newAge) {
this.changeName(newName=newName);
this.changeAge(newAge=newAge);
}
}
All works fine if I instanciate it, and if mingle with it a bit this is the code and output:
let p1 = new Person('George', 20);
console.log(p1);
p1.changeName(newName='Robert');
console.log(p1);
p1.changeAgeAndName(newName='Joe', newAge=23);
console.log(p1);
Person { name: 'George', age: 20 }
Person { name: 'Robert', age: 20 }
Person { name: 'Joe', age: 23 }
Now, let's say I want to use changeAgeAndName inside the constructor like so (specifying the parameter names for the variables):
constructor(name, age) {
this.changeAgeAndName(newName=name, newAge=age);
}
I get an error:
this.changeAgeAndName(newName=name, newAge=age);
ReferenceError: newName is not defined
But if I don't specify the parameter names, all is fine:
constructor(name, age) {
this.changeAgeAndName(name, age);
}
Eventual Output:
Person2 { name: 'Mike', age: 40 }
If I specify the parameter names outside the constructor, all is fine as well. I like to be as explicit as possible when coding, so I was wondering what I may be doing wrong. Also, I was curious about perhaps yet another example of peculiar JS behavior. Thank you!