arozwalak
7/12/2015 - 11:16 AM

Javascript: Object Literal

Javascript: Object Literal

// start with an empty object
var dog = {};

// add one property
dog.name = "Benji";

// add method
dog.getName = function () {
  return dog.name;
};

// remove properties/methods
delete dog.name;
var dog = {
  name: "Benji",
  getName: function () {
    return this.name;
  }
// create object using built-in contstructor
var car = new Object();
car.goes = "far";
// WARNING
var o = new Object();
console.log(o.constructor === Object); // true

var o = new Object(1);
console.log(o.constructor === Number); // true
console.log(o.toFixed(2)); // "1.00"

var o = new Object("I am a string");
console.log(o.constructor === String); // true
console.log(typeof o.substring); // "function"

var o = new Object(true);
console.log(o.constructor === Boolean); // true

Custom Constructor Functions

var adam = new Person("Adam");
adam.say(); // "I am Adam"

var Person = function (name) {
  this.name = name;
  this.say = function () {
    return "I am " + this.name;
  };
};

// Adding method to this result creation 
// new function in memory every time you call
// new Person(). Instead better way is to add
// methods to the prototype of Person

Person.prototype.say = function () {
  return "I am " + this.name;
};
var Objectmaker = function () {
  // this `name` property will be ignored
  // because the constructor
  // decides to return another object instead
  this.name = "This is it";
  
  // creating and returning a new object
  var that = {};
  that.name = "And that's that";
  return that;
};

// test
var o = new Objectmaker();
console.log(o.name); // "And that's that"

Patterns for Enforcing new

// Using that
// Problem with this is pattern is that the link
// to the prototype is lost, so any members
// you add to the Waffle() prototype will not be // available to the objects
function Waffle() {
  var that = {};
  that.tastes = "yummy";
  return that;
}

function Waffle() {
  return {
    tastes: "yummy"
  };
}

Self-Invoking Constructor

function Waffle() {
  if (!(this instanceof Waffle)) {
    return new Waffle();
  }
  
  this.tastes = "yummy";
}

Waffle.prototype.wantAnother = true;

// testing invocations
var first = new Waffle(),
    second = Waffle();
    
console.log(first.tastes); // "yummy"
console.log(second.tastes); // "yummy"

console.log(first.wantAnother); // true
console.log(second.wantAnother); // true