- 1
Why I will add new property to an object using prototype property?
If I need to add a new property to an object I can done this by adding them inside the object. for an example function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } to add nationality to this object I just can do this function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; this.nationality = "English"; } so when and why I will use prototype property to do this?
9 Réponses
+ 8
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var man=new Person();
//what if you now suddenly decide man needs an additional property?
man.prototype.hairColor="red";
prototype also allows to add additional properties to predefined methods.
Array.prototype.dance=5:
+ 2
There are many ways to achieve a goal in Javascript.
I'll say it won't have any side effects on your program
+ 2
which is good ide for node.js,js,angular js,html,css
+ 1
Thanks
+ 1
I don't do JS a lot, but I think if you wanted a subtype you can add more properties as well as inheriting the parent ones using this. I would think generally if it's the same class you should put them all together which is helpful for readability
0
Nayem There are many ways to create an objects ,as well as assigning properties.
If you feel like using functions,use it, else if you want to use the Object.prototype method, you could also use it
It's a matter of choice
0
is there any difference between these tow method ? if I use theme are they gonna make any difference in my project?
0
Brains🇳🇬
Let me ask you this, does it generate an error if you use the "dot" property on Objects created by functions?
0
no it doesn't