+ 2
how to update age with updateAge method parameter
im trying to pass a value inside updateAge method to update object properties i cant update person1.age values it returns the same value which is 12 original property plz help me how to update using my existing method function Person(Name, age, color){ this.Name= Name; this.age= age; this.color=color; this.updateName= function(ages){ this.age = this.age + ages; }; } let person1 = new Person("a", 12, "white"); let person2 = new Person("b", 25, "bkack"); person1.updateName(21); console.log(person1.age);
5 Respostas
+ 2
Hi daneillonge,
You are now doing a sum of the updated age and the initial age which results in 33.
Remove the 'this.age' before '+ ages' will fix the issue since it won't sum both values:
function Person(Name, age, color){
this.Name= Name;
this.age= age;
this.color=color;
this.updateName= function(ages){
this.age = ages;
};
}
let person1 = new Person("a", 12, "white");
let person2 = new Person("b", 25, "bkack");
person1.updateName(21);
console.log(person1.age); //_ 21
Additional:
U can write this in ES6 since you have more options inside constructors and classes with less code.
class Person{
constructor(name,age,color){
this.name = Name;
this.age = Age;
this.color = Color;
}
setnewAge(Age){
this.age = Age;
}
}
let person1 = new Person("a", 12, "white");
let person2 = new Person("b", 25, "bkack");
person1.updateName(21);
console.log(person1.age); //_ 21
+ 1
thanks by the way i solve it i forget i have to assign the update age instead of adding it incrementing confusing happen in coding world hehe😊
+ 1
i think it would look cool if we add arrow function
+ 1
i have question what is the purpose of using function setnewAge outside constructor instead of method inside constructor is it both similar or there is code efficiency
0
daneillonge,
The class syntax is not implementing a new object-oriented model to JavaScript.
JavaScript classes provide a much simpler and clearer syntax to create objects.
In ES6 the function is called a static method of the class.
Additional you can extent a class to combine the current class with another class.
https://youtu.be/CwAU1wYeHiM
The arrow function is a anonymous function which has a shorter syntax. and it is indeed nice to use😊