prototypes and constructors in javascript

I usually do not need to write code using neither constructors nor prototypes in Javascript. So, I always forget how to write them when I need to use them.

Constructor

  Say = function(){
    this.hello = function() {
      return "Hello";
    }
  }

  var say = new Say();
  say.hello()

  // "Hello"

Prototype

  function Say() {}
   Say.prototype.hello = function() {
    return "Hello";
  }

  var say = new Say();
  say.hello()

  // "Hello"

Helpful Links

Use of ‘prototype’ vs. ‘this’ in JavaScript?

Advantages of using prototype, vs defining methods straight in the constructor?

comments powered by Disqus