Sunday, November 6, 2011

Be careful "this" in Javascript Object

Consider the following javascript code:
What if I remove the this in method increment()?, like this:

I must admit at first I wrote the code like the second, But it was wrong.
As a Java programmer, I thought keyword this in javascript will like java this always refer to the object owner, so this can be omitted. But I was wrong, the code above is wrong, because javascript requires you to use this keyword explicitly, otherwise it will treat variable value as undefined. It seems javascript will treat variable value as local variable, except you specify this explicitly.

From this mistake, I understand that the experience in java is not working in javascript, if you want to access the class level variable in javascript method, you have to explicitly using this. Be careful for "this"!

No comments:

Post a Comment