Skip to content
der-On edited this page Dec 16, 2014 · 6 revisions

On this page we want to collect common patterns that do make use of new or prototype but in a more optimized and more readable way.

prototype

Using prototype to define methods and properties shared across subclasses can be very verbose if you write it the old JS way.

// standard js

function User(name) {
  this.name = name;
}

User.prototype.greet = function(getting) {
  console.log(this.name + ' says "' + (greeting || 'hi!') + '"')
}

User.prototype.sharedProperty = 'baz'

var john = User('John');
john.greet('howdy!'); // logs 'John says "howdy!"' to console
john.sharedProp // 'baz'

Despite beeing verbose another downside is that we cannot use private functions or variables within methods defined this way.

Instead we can use a closure to define our prototype:

// almost rethink.js

function User(name) {
  this.name = name;
}

User.prototype = new (function(){
  var privateProp = 'secret'

  this.greet = function(getting) {
    console.log(this.name + ' says "' + (greeting || 'hi!') + '"')
  }

  this.sharedProp = 'baz'
})();

We can modify this to not use new and less this:

// rethink.js

function User(name) {
  this.name = name;
}

User.prototype = (function(){
  var privateProp = 'secret'

  function greet(getting) {
    console.log(this.name + ' says "' + (greeting || 'hi!') + '"')
  }

  var sharedProp = 'baz'
  
  // return public methods and shared properties
  return {
   sharedProp: sharedProp,
   greet: greet
  }
})();

Performance of these methods is not very different at all.

Clone this wiki locally