// We are establishing an object to use as
// a prototype/base/template for other objects
var vehicleTemplate = {
name: "Car",
drive: function () {
console.log("Weeee. I'm driving!");
},
panic: function () {
console.log("Wait. How do you stop this thing?");
}
};
// Use Object.create to instantiate a new car
var yourCar = Object.create(vehicleTemplate);
// Now we can see that one is a prototype of the other
console.log("Your car", yourCar);
// We can augment our template
vehicleTemplate.speedHoles = true;
console.log("Augmented Car", yourCar);
// And if we set a property on our car
// it will set itself locally (not affecting the prototype)
yourCar.speedHoles = false;
console.log("Augmented car with no speed holes", yourCar);
// You can also use Object.create to
// create an object with a prototype
// and set additional properties on the fly
var car = Object.create(vehicleTemplate, {
"year": {
value: "1999",
// writable:false, configurable:false by default
enumerable: true
},
"model": {
value: "Ford",
enumerable: true
}
});
console.log(car);
// Implementing Prototype Pattern
// without using Object.create()
// ECMAscript 3
var vehiclePrototype = {
init: function ( carModel ) {
this.model = carModel;
},
getModel: function () {
console.log( "The model of this vehicle is.." + this.model);
}
};
var vehicle = function(model) {
function F() {};
F.prototype = vehiclePrototype;
var f = new F();
f.init( model );
return f;
};
var car = vehicle("Ford Escort");
car.getModel();
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.