Return to Snippet

Revision: 14466
at June 4, 2009 17:19 by segdeha


Updated Code
// consider:
function Grape(type) {
  this.type = type || 'Xynomavro';
}

Grape.prototype.squash = function () {
  return this.type.substring(0, 3);
};

var grape = new Grape();

alert(grape.squash());

// versus:
var grapes = {
  barrel : [],
  squash : function (grape) {
    return grape.substring(0, 3);
  }
};

grapes.barrel.push('Nebbiolo');

alert(grapes.squash(grapes.barrel[0]));

Revision: 14465
at June 4, 2009 17:13 by segdeha


Initial Code
// consider:
function Grape(type) {
  this.type = type || 'Xynomavro';
}

Grape.prototype.squash = function () {
  return this.type.substring(0, 1);
};

var grape = new Grape();

alert(grape.squash());

// versus:
var grapes = {
  barrel : [],
  squash : function (grape) {
    return grape.substring(0, 1);
  }
};

grapes.barrel.push('Nebbiolo');

alert(grapes.squash(grapes.barrel[0]));

Initial URL


Initial Description
Assign methods to a Function prototype when you intend to create instances of the type of object. Use object literals when you just need a container for functions.

Initial Title
When to use the prototype of a Function

Initial Tags
javascript, function

Initial Language
JavaScript