Iacutone.rb

coding and things

Prototypes and Constructors in Javascript

| Comments

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

1
2
3
4
5
6
7
8
9
10
  Say = function(){
    this.hello = function() {
      return "Hello";
    }
  }

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

  // "Hello"

Prototype

1
2
3
4
5
6
7
8
9
  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