All pages
Powered by GitBook
1 of 9

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Objects

The primitive types of JavaScript are true, false, numbers, strings, null and undefined. Every other value is an object.

In JavaScript objects contain propertyName: propertyValue pairs.

Delete

delete can be used to remove a property from an object. It will remove a property from the object if it has one. It will not look further in the prototype chain. Removing a property from an object may allow a property from the prototype chain to shine through:

var adult = {age:26},
    child = Object.create(adult);
    child.age = 8;

delete child.age;
 /* Remove age property from child, revealing the age of the prototype, because then it is not overriden. */
var prototypeAge = child.age;
 // 26, because child does not have its own age property.

Mutable

The difference between objects and primitive values is that we can change objects, whereas primitive values are immutable.

var myPrimitive = "first value";
    myPrimitive = "another value";
 // myPrimitive now points to another string.
var myObject = { key: "first value"};
    myObject.key = "another value";
 // myObject points to the same object.

Reference

Objects are never copied. They are passed around by reference.

 // Imagine I had a pizza
var myPizza = {slices: 5};
 // And I shared it with You
var yourPizza = myPizza;
 // I eat another slice
myPizza.slices = myPizza.slices - 1;
var numberOfSlicesLeft = yourPizza.slices;
 // Now We have 4 slices because myPizza and yourPizza
 // reference to the same pizza object.
var a = {}, b = {}, c = {};
 // a, b, and c each refer to a
 // different empty object
a = b = c = {};
 // a, b, and c all refer to
 // the same empty object

Global footprint

If you are developing a module, which might be running on a web page, which also runs other modules, then you must beware the variable name overlapping.

Suppose we are developing a counter module:

Note: this technique is often used with closures, to make the internal state immutable from the outside.

The module now takes only one variable name — myCounter. If any other module on the page makes use of such names like number or isGreaterThanTen then it's perfectly safe, because we will not override each others values;

var myCounter = {
    number : 0,
    plusPlus : function(){
        this.number : this.number + 1;
    },
    isGreaterThanTen : function(){
        return this.number > 10;
    }
}

Properties

Object's property is a propertyName: propertyValue pair, where property name can be only a string. If it's not a string, it gets casted into a string. You can specify properties when creating an object or later. There may be zero or more properties separated by commas.

var language = {
    name: 'JavaScript',
    isSupportedByBrowsers: true,
    createdIn: 1995,
    author:{
        firstName: 'Brendan',
        lastName: 'Eich'
    },
 // Yes, objects can be nested!
    getAuthorFullName: function(){
        return this.author.firstName + " " + this.author.lastName;    
    }
 // Yes, functions can be values too!
};

The following code demonstates how to get a property's value.

var variable = language.name;
 // variable now contains "JavaScript" string.
    variable = language['name'];
 // The lines above do the same thing. The difference is that the second one lets you use litteraly any string as a property name, but it's less readable. 
    variable = language.newProperty; 
 // variable is now undefined, because we have not assigned this property yet.

The following example shows how to add a new property or change an existing one.

language.newProperty = 'new value';
 // Now the object has a new property. If the property already exists, its value will be replaced.
language['newProperty'] = 'changed value';
 // Once again, you can access properties both ways. The first one (dot notation) is recomended.

Enumeration

The for in statement can loop over all of the property names in an object. The enumeration will include functions and prototype properties.

var fruit = {
    apple: 2,
    orange:5,
    pear:1
},
sentence = 'I have ',
quantity;
for (kind in fruit){
    quantity = fruit[kind];
    sentence += quantity+' '+kind+
                (quantity===1?'':'s')+
                ', ';
}
 // The following line removes the trailing coma.
sentence = sentence.substr(0,sentence.length-2)+'.';
 // I have 2 apples, 5 oranges, 1 pear.

Prototype

Every object is linked to a prototype object from which it inherits properties.

All objects created from object literals ({}) are automatically linked to Object.prototype, which is an object that comes standard with JavaScript.

When a JavaScript interpreter (a module in your browser) tries to find a property, which You want to retrieve, like in the following code:

var adult = {age: 26},
    retrievedProperty = adult.age;
 // The line above

First, the interpreter looks through every property the object itself has. For example, adult has only one own property — age. But besides that one it actually has a few more properties, which were inherited from Object.prototype.

var stringRepresentation = adult.toString();
 // the variable has value of '[object Object]'

toString is an Object.prototype's property, which was inherited. It has a value of a function, which returns a string representation of the object. If you want it to return a more meaningful representation, then you can override it. Simply add a new property to the adult object.

adult.toString = function(){
    return "I'm "+this.age;
}

If you call the toString function now, the interpreter will find the new property in the object itself and stop.

Thus the interpreter retrieves the first property it will find on the way from the object itself and further through its prototype.

To set your own object as a prototype instead of the default Object.prototype, you can invoke Object.create as follows:

var child = Object.create(adult);
 /* This way of creating objects lets us easily replace the default Object.prototype with the one we want. In this case, the child's prototype is the adult object. */
child.age = 8;
 /* Previously, child didn't have its own age property, and the interpreter had to look further to the child's prototype to find it.
 Now, when we set the child's own age, the interpreter will not go further.
 Note: adult's age is still 26. */
var stringRepresentation = child.toString();
 // The value is "I'm 8".
 /* Note: we have not overridden the child's toString property, thus the adult's method will be invoked. If adult did not have toString property, then Object.prototype's toString method would be invoked, and we would get "[object Object]" instead of "I'm 8" */

child's prototype is adult, whose prototype is Object.prototype. This sequence of prototypes is called prototype chain.

Creation

There are two ways to create an object in JavaScript:

  1. literal

     var object = {};
      // Yes, simply a pair of curly braces!

    Note: this is the recomended way.

  2. and object-oriented

     var object = new Object();

    Note: it's almost like Java.