Ellatronic
Design Portfolio

Blog

JavaScript: Understanding the Weird Parts (Part 4)

Objects and Functions

  • In JS, objects and functions are related so much that they can be considered the same subject.

Objects and the Dot

  • Objects are collections of name/value pairs whose values can be other name/value pairs.
  • Objects can have primitive properties (boolean, number, etc.), object properties (child, etc.), and function methods.
  • The core object will have an address in the computer's memory and references to the different properties and methods
var person = new Object();
person["firstName"] = "Ella";
  • [ ] computed member access - access and set properties
console.log(person.firstName);
  • Preferred approach is to use the dot operator over the brackets because it is cleaner, clearer, and easier to debug
  • Use the dot operator unless accessing a property with a dynamic string

Objects and Object Literals

var person = {}; //create a new object by using 
                 //curly braces
var person = {
    firstName: 'Ella',
    lastName: 'Chiang',
    address: {
        street: '21 Street',
        city: 'Amazing Town'
        }
}

greet({
    firstName: 'Pickle', //create an object 
                         //on the fly while 
                         //calling a function
    lastName: 'Chiang'
});
  • This object can be used whereever a variable can be used.
Ella.address2 = {
    street: '888 2nd St'
};
  • Methodologies (dot notation and object literal) can also be mixed and matched

Faking Namespaces

  • namespace - a container for variables and functions to keep variables and functions with the same name separate
    • JavaScript does not have namespaces
var greet = 'Hello!';
var greet = 'Hola!';

console.log(greet); 
//-> Hola!, Hello! is overwritten

var english = {}; //create an object to
var spanish = {}; //use as a container

english.greet = 'Hello!';
spanish.greet = 'Hola!';

console.log(english); //-> Hello!
  • When an object is used as a container, there is no namespace collision (two things named the same) and Hello! is not overwritten.
english.greetings.greet = 'Hello!'; 
//produces Uncaught TypeError: 
//cannot set property 'greet' of undefined
  • dot is a left associative operator. Calling greetings on english yields undefined since english is empty.
  • Create english.greetings = {}; first, then use .greet.