Skip to content
Advertisement

How to block parameters of function which is in prototype overrided after created another object

To avoid copies of the same function I hear that functions must define in prototype. And I hear that OOP inheritance is suck that is why I tried to use factory function when go deep in Javascript. But I have a problem in the following code. I defined all functions in prototype and create two object, emp and emp2. But after defined emp2, parameters of emp is overrided. So what is benefit of factory function and prototype?

JavaScript

Advertisement

Answer

It doesn’t work when using this keyword without new keyword.

JavaScript

With new keyword

JavaScript

According to these result: new keyword just makes the prototype of the this object refer to createEmployee.prototype, like the Object.create call did before. And return this object. When calling a function with new keyword or just calling regular function this object create autumaticly.

But we dont need to use this keyword in createEmployee factory function. We just need this keyword in our object function like work and eat.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement