0

Ok so I'm learning some topics and I'm learning prototypes. I see that this works:

function Person(name) {
    this.name = name || 'Luis Felipe Zaguini';

    this.sayHi = function() {
        console.log(`Hey there, ${this.name}!`);
    }

    this.sayGoodBye = function() {
        console.log(`Good bye, ${this.name}!`);
    }
}

let me = new Person();
me.sayHi();

let other = new Person('Other');
other.sayGoodBye();

But that also works:

function Person(name) {
    this.name = name || 'Luis Felipe Zaguini';

    this.sayHi = function() {
        console.log(`Hey there, ${this.name}!`);
    }
}

Person.prototype.sayGoodBye = function() {
    console.log(`Good bye, ${this.name}!`);
}

let me = new Person();
me.sayHi();

let other = new Person('Other');
other.sayGoodBye();

They end up 'in the same way'. Which version is better? Are there some disadvantages? It seems to me that the first way (defining methods inside the function object) looks clearer. What do you people think?

  • 1
    prototypes allow you to reuse the same code for all instances. If you need to instantiate many instances that would be an advantage (prototyped properties however are simply moved to the instance). –  Mar 02 '17 at 00:38
  • Hmmm yes, but the methods defined inside the function object allow it as well. – Luis Felipe Zaguini Mar 02 '17 at 00:40
  • 3
    they become new fresh copies, while prototyped ones are "referenced". –  Mar 02 '17 at 00:41
  • Oh, I see the difference. Great! Is it worth using that way instead of defining inside the function or should I just let it go? – Luis Felipe Zaguini Mar 02 '17 at 00:44
  • 1
    If you anticipate many instances I would recommend prototypes. –  Mar 02 '17 at 00:45
  • 1
    Another thing you might want to look at is ES6 classes. Under the hood, they use prototypes however the syntax is a bit cleaner. They are unfortunately not supported natively in browsers today though – derp Mar 02 '17 at 00:47
  • 1
    If you need to do runtime introspection of your objects, you'll find that defining methods in the constructor is a very bad idea. I'll give an answer later if it isn't already answered. This actually require a lengthy reply which I haven't got the time for now. But in summary, always use the prototype. ALWAYS. – natnai Mar 02 '17 at 00:52

0 Answers0