View Full Version : Problem in javascript

03-20-2005, 11:55 AM

I want to know how the following code executes.

function fn(var)
return this.var3[var4];

The above function will be called when the menu is clicked in javascript.
Plz help me

03-20-2005, 02:16 PM
I want to know how the following code executes.It's impossible to be specific as there isn't enough information from this snippet alone, but I could walk through it.

function fn(var)First of all, use of the var keyword like this is a mistake as it is a reserved word and cannot be used as a variable identifier. The code shouldn't run at all, but I'll ignore that for the moment.

this.var1=function(var2)The value of the this operator is an object reference. What that reference is depends on how fn is called. It could be the global object (the same as window in most user agents) or it could be another object. In any case, this statement is also in error as the right-hand side of the assignment isn't a function call. Again, function is a reserved word so it can't be an identifier, and that isn't a function expression. However, if it was valid, a value would be assigned to the var1 property on the object referenced by this.

return this.var3[var4];The expression here contains bracket notation. With ECMAScript, there are two ways to access properties: the dot notation, and bracket notation. The difference is that you can use expressions with bracket notation, but only literal identifiers with dot notation. In other words, obj.property and obj['property'] are equivalent. The value of var4 will be used to access a property on the object referenced by this.var3. You can read more (http://www.jibbering.com/faq/faq_notes/square_brackets.html) in the FAQ notes for the comp.lang.javascript newsgroup.

I realise that the descriptions above probably aren't very useful, and they are probably difficult to understand. But without more information, there is little to give other than a technical description. Without seeing what fn is doing, I can't show easy-to-read examples.