Js - Object.create

by Charlie Winfrey

JavaScript

// 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 
// createn 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();