What is the advantage or different adding a function onto the prototype object versus simply declaring it on the constructor's variable?
this is the same, this is how we call Person
const James = new Person('James')
James.greet()
Adding greet to prototype object
const Person = name => {
this.name = name
}
Person.protoype.greet = () => console.log(`my name is ${this.name}!`)
Adding greet to constructor
const Person = name => {
this.name = name
this.greet = () => console.log(`my name is ${this.name}!`)
}
Does adding greet to constructor make duplicate of function when we call Person multiple times? I know the disavatange of object method have this problem, for example
const Person = () => ({
name: '',
greet: () => console.log(`my name is ${this.name}!`)
})
const James = Person('James') //greet copy 1
James.greet()
const Alice = Person('Alice') //greet copy 2
Alice.greet()
Does adding greet to constructor make duplicate of function when we call Person multiple times?Yes. Every time a script runs across thefunctionkeyword (or=>), it will create a new function. Better to have one single function all class members reference than to have tons of identical functions.Adding greet to constructorand useAdding greet to prototype object?. As I know prototype is a shared function, so any new instance won't cause memory leak if we have tons of instance.var a = new Person("a"), b = new Person("b");addinggreetit to prototype:a.greet === b.greet => true(only one function shared by all instances ofPerson) whereas adding it in the constructor:a.greet === b.greet => false(each instance gets its own copy ofgreetwhich is redundant and wasteful).