// Straight from the mouth of Crockford...
// @spec is information about the new instance
// @my is a bundle of shared secrets used by the constructors, but it is optional
var car = function(spec) {
// private variables
var that = {}, odometer=0;
// private method
var increaseOdometer = function(i) {
odometer+=i;
};
var checkOdometer = function() {
return odometer;
}
// privileged methods
that.getName = function() {
return spec.name;
};
// we can define a public method by referencing a private method
// this can make it easier to use the function across the constructor w/out having to include "that."
that.checkOdometer = checkOdometer;
that.increaseOdometer = increaseOdometer;
return that;
}
var toyota = car({name: "Toyota", year: 1990});
console.log(toyota);
var tesla = car({name: "Model S"});
console.log(tesla, tesla.checkOdometer());
tesla.increaseOdometer(10);
console.log(tesla, tesla.checkOdometer());
console.log(tesla, toyota.checkOdometer());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.