Jack Hamilton

2016/02/22: JavaScript Cheat-Sheet: Objects and Functions Examples

Table of Contents

object literal


var phonebookEntry = new Object(); // alternative 1
var phonebookEntry = {};           // alternative 2

phonebookEntry.name = 'The Ghostbusters';    // can add properties "outside" via dot-notation
phonebookEntry["number"] = '(650) 555-2368'; // can use bracket notation so long as property is quoted
phonebookEntry.phone = function() {          // objects can contains functions
  console.log('Calling ' + this.name + ' at ' + this.number + '...');
};

Object Literal: Alternative creation. Uses colon syntax, similar to key-value pairs in a Ruby hash.


var phonebookEntry = {
    name: 'The Ghostbusters',
    number: '(650) 555-2368',
    phone: function() {
        console.log('Calling ' + this.name + ' at ' + this.number + '...');
    }
};

console.log(phonebookEntry.hasOwnProperty('phone')); // true
phonebookEntry.phone(); // Calling The Ghostbusters at (650) 555-2368...

public functions (constructor and prototype)


// Constructor function (public)
function Person(name,age) {
  this.name = name;
  this.age = age;
}

// Prototypes (public): added to all objects made by constructor (saves memory)
Person.prototype.speak = function(){
	console.log("Hi");
}

private functions (2 types, including the hoisted version)
privileged functions (has access to private and public vars)


function Person(first,last,age) {
   this.firstname = first;
   this.lastname = last;
   this.age = age;
   var bankBalance = 7500;

   // Function Expression
   // private due to "var" keyword
   // can only be used internally, and only after declared at run-time.
   var returnBalance = function() {
      return bankBalance;
   };
   
   // Function Declaration
   // private; an alias of form: var x = function (){...};
   // but hoisted and can be used internally before declared at run-time.
   function returnBalanceAlso() {
      return bankBalance;
   }
       
   // privileged due to "this" keyword; accessible by public and can access private methods/vars
   this.askTeller = function() {
       return returnBalance
   };
}

var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);

static function (no need to instantiate)


function BoW() {}
BoW.get_official_name = function() {
    var bank_name = "Bank of the World";
    return bank_name;
};

console.log("I bank at " + BoW.get_official_name() + "!");  // I bank at Bank of the World!