Javascript Object Oriented Design - Javascript this








object methods

We can add a method to an object in the same way that we would add a property.

The following code, the book variable is assigned an object literal with a name property and a method called writeLine.


var book = { 
    name : "Javascript", 
    writeLine : function() { 
        console.log(book.name); 
    } 
}; 

book.writeLine();        

The code above generates the following result.





The this Object

Every scope in JavaScript has a this object that represents the calling object for the function.

In the global scope, this represents the global object, for example window object in web browsers.

When a function is called while attached to an object, the value of this is equal to that object by default.

We can rewrite the code from the previous example to use this:


var book = { 
    name : "Javascript", 
    writeLine : function() { 
        console.log(this.name); 
    } 
}; 

book.writeLine();       

The code above generates the following result.

The following code shows that we can reuse the function on different objects.


function writeLineForAll() { /*  w  ww  . j  a  v  a 2s.  com*/
    console.log(this.name); 
} 

var book1 = { 
    name : "Javascript", 
    writeLine : writeLineForAll 
}; 

var book2 = { 
    name : "CSS", 
    writeLine : writeLineForAll 
}; 

var name = "HTML"; 

book1.writeLine();     
book2.writeLine();    

writeLineForAll();     

The code above generates the following result.