1. The Constructor Pattern

Created Thursday 19 December 2013

  1. 3 common ways to create new objects in JS:
    1. var newObject = {};
    2. var newObject = Object.create(null);
    3. var newObject = new Object();
  2. 4 ways to assign keys and values to an object:
    1. Dot syntax:
      1. Set properties:
        1. newObject.someKey = "Hello World";
      2. Get properties:
        1. var key = newObject.someKey;
    2. Square bracket syntax:
      1. Set properties:
        1. newObject["someKey"] = "Hello World";
      2. Get properties:
        1. var key = newObject["someKey"];
    3. __Object.defineProperty (ECMAScript 5 only compatible (http://kangax.github.com/es5-compat-table/)):__
      1. Set properties:
        1. Way 1:
Object.defineProperty(newObject, "someKey", {
value: "someValue",
writable: true,
enumerable: true,
configurable: true
});
  1. Way 2:
var defineProp = function(obj, key, value){
config.value = value;
Object.defineProperty(obj, key, config);
};
var person = Object.create(null);
defineProp(person, "car", "Delorean");
defineProp(person, "dateOfBirth", "1981");
defineProp(person, "hasBeard", false);
  1. Object.defineProperties:
    1. Set properties:
Object.defineProperties(newObject, {
"someKey" : {
value: "Hello World",
writable: true
},
"anotherKey" : {
value: "Foo bar",
writable: false
}
});
  1. Basic Constructors:
    1. Cons:
      1. Difficult inheritance
      2. Methods are redefined for each new object creation
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function() {
return this.model + " has done " + this.miles + " miles";
};
}
var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);
console.log(civic.toString());
console.log(mondeo.toString());
  1. Constructors With Prototypes:
function Car(model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.toString = function() {
return this.model + " has done " + this.miles + " miles";
};
var civic = new Car("Honda Civic", 2009, 20000);



Backlinks: