JavaScript – A Different Beast, Part-6: Objects without Classes

This

Following code sample uses the ‘this’ keyword. ‘this’ is a special variable that always points to the current object.

//Code-4 - Object members using constructor function
function car(name,color){
    this.name = name;
    this['color'] = color;
    this.run = function() {
        console.log('started ' + this.name);
    }
    this['brake'] = function() {
        console.log('stopped ' + this.name);
    }
}
//end of constructor definition

//instantiating objects using the constructor
var lamborgini = new car('lamborgini', 'green'); //preferred way
var ferrari = new(car)('ferrari','red'); //an ugly way of doing the same thing
console.log(lamborgini);
console.log(ferrari);

//test drive
lamborgini.run(); //started lamborgini
ferrari.brake(); //stopped ferrari.  >>how can you brake the ferrari when its not running. We should fix this.
lamborgini.run(); //started lamborgini >>isn't it already running?? We can fix these problems with a private variable

What if you use this outside an object? Code-5 below shows an example.

//Code-5 - Example: this


<script type="text/javascript">// <![CDATA[
	document.write('Top='+this+'       '); 			
        function f2(){ 	
            document.write('f2='+this+'       '); 			
        }
 	function f1() { 				
            document.write('f1='+this+'       '); 				
            f2();
 	} 			
        f1();
// ]]></script></pre>
<h2>Example: this</h2>
<pre>


Output on Firefox:

Output in Firefox

Output in Firefox

As you can see from the output the variable this always points to the global object – in this case the window object within a browser – irrespective of the scope!

Understanding this

this variable has a number of interesting properties that one should be aware of:

1.Value of ‘this’: ‘this’ normally points to the global object. But it is assigned a new value when an object gets created. See code-6 below:

//Code-6 - 'this' and object creation
function car(){
    this.name = 'dodge';
    console.log(this);
}

car();    //function call. 'this' points to the global object and therefore prints the Global Object
var mycar = new car();   //'new' creates a new object and assigns it to 'this'. Prints the car object

2.’this’ and member functions: Only member functions can use ‘this’ to get the current object. See code-7 below.

//Code - 3.7 - 'this' and member functions
var mycar = {
	name : 'ferrari',
	color: 'red',
	method1 : function() { console.log(this); }
};

mycar.method1(); //Object { name="ferrari", color="red"}

function foo(){
	console.log(this);
}

//making foo a member of mycar
mycar.method3 = foo;
mycar.method3(); //Object { name="ferrari", color="red"}

mycar.method2 = function(){  foo();  };
mycar.method2();//prints Window

In the code above, fun starts at line-15. Foo is made a member of my car which makes this in foo to point to the object. In line-18, foo is called from a another member function. Since foo itself is not a member this points to the global object in that case.

3. Scope of this : this knows the context and always points to the correct object. See code-8 below.

//Code - 3.8 - scope of 'this'
function foo(){
	console.log(this);
}

var mycar = {
	name : 'ferrari',
	color: 'red',
	engine: {
		power : '350BHP',
		topSpeed: '300kph',
		print : foo,
	}
};

mycar.engine.print(); // Object { power="350BHP", topSpeed="300kph"}

As you can see, this in engine’s method points to the engine object and not to the car object.

Advertisements

About Rahul Mohan

Technical researcher interested in model-driven development of enterprise business applications. Passionate about web technologies and a huge admirer of open-source especially in the Java landscape. When I am not doing any of the above you can find me with my camera (www.flickr.com/photos/rahulmohan/) or listening to music. (In fact, the title of the blog is inspired by Led Zeppelin's Physical Graffiti. )

Posted on May 21, 2011, in JavaScript, Tutorial and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: