Object in Javascript, a C++ programmer’s point of view

March 20, 2009 at 4:59 am 1 comment

There is no shortage of books and blog posts talking about OOP in Javascript. But the more I read, the more confused I am. Because I am a C++ programmer and Javascript and C++ are so different. Until I found this ppt. After read it a few times, played in Firebug, and read some open source Javascript projects, I think I understand the idea of Object now.

In this post, I use Firebug’s Javascript Console to demonstrate my codes and their result. Firebug is a Javascript debugger for Firefox. It is also a good place to test drive Javascript.

Except a few primitive types, everything in Javascript is an Object. Objects are implemented as map (hash table). Consider the following object:
var user = { name : 'John', age : 20 };
You can either write
Both will give you the same result. Member of an object can be a primitive variable, an object, or a function. Actually, in Javascript, function is a kind of object.

In Javascript, objects can only be accessed by reference. That means if you assign an object to another, you just created another reference to the same object. In this aspect, Javascript behaves like Java. For example:
>>> var o1 = { id : 1 };
>>> var o2 = o1;  // o1 and o2 point to the same object
>>> var o2.id = 2;
>>> o2.id = 2;
>>> o1.id    // o1.id get changed too

As I said before, in Javascript, a function is an object. It is just a object that can be called. You can think of it as a functor in C++. Actually, function has more “functions” in Javascript. A function can be called in 2 ways, as a normal function or as a constructor. When you write
a = myfunc();
you are calling myfunc() as a normal function. Instead, if you write
a = new myfunc();
you are calling myfunc() as a constructor.

When called as a constructor, a function first create a object called “this”. Then, it go though the function as usual. When the function returns, “this” will be returned and the original return will be discarded. Consider the following code:
function UserAccount(name, age) {
    this.name = name;
    this.age = age;
    return "I'll not be returned when called as a constructor";

var user1 = new UserAccount('John', 20);

user1 will be an object consists “name” and “age”.  Here, “this” is quite confusing for C++ programmers. It has nothing to do with “this” pointer in C++. “this” is a object that browser created for you when you call a function as a constructor. In the above sample, we modified “this” and “this” was passed to user1 implicitly.

Another widely used and confusing feature is prototype. Javascript implements inheritance by prototype. But in  practice, prototype is simply used as another way to initialize a object. Then, why another way? To get the answer, we need to analyze the underling implementation.

 Every object has a hidden member called __proto__, which points to the object’s base object. When you try to read a member of an derived object, browser will search in the object’s properties first. If the derived object does not have the requested property, browser will search in its __proto__, then the __proto__’s __proto__. If you want to write into a non-existing member, browser will create the member and write into it. At the same time, every function has a property called “prototype”. By default, prototype is an empty object. You can modify it to fit your needs. When a function is called as a constructor, browser creates a object called “this” and points its “__proto__” to the function’s “prototype”. Since __proto__ is just a reference, the function’s prototype is shared by all object it constructed. The following code shows the underling implement of prototype:
>>> function UserAccount() {}
>>> UserAccount.prototype.name = 'John';
>>> user1 = new UserAccount();    // user1 does not have name, but prototype has one.
Object name=John
>>> user2 = new UserAccount();    // prototype is shared by user1 and user2
Object name=John
>>> user1.name = 'Tom';        // user1 has its own name now
>>> user2.name        // user2 is still using the prototype's name
>>> UserAccount.prototype.name = 'Alice';    // change prototype's name
>>> user1.name    // user1 unaffected
>>> user2.name    // user2 is still using the prototype's name

That’s it. Hopefully this post can help C++ users pick up Javascript easier.


Entry filed under: Web Programming. Tags: .

Lock-free programming Porting C++ code to Linux kernel

1 Comment Add your own

  • 1. fire risk assessment form  |  August 3, 2013 at 11:37 am

    Another thing to consider is keeping the area around the fire site.

    He is station commander at Bellshill Community Fire Station were dispatched to the scene.
    Pretty much everything is while many offered
    about fire safety training And Education down sides or even pros.

    Furthermore, one fire extinguisher every 1, 500, the Citizens Budget Commission says, would not limit the department’s ability to respond. A spark can create havoc because the summer heat is intense this year, having won a category last year.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


March 2009
« Jun   Apr »

Most Recent Posts

%d bloggers like this: