views:

33

answers:

3

I'm trying to get this to work, but it doesn't:

var i; 

i.test = function() { 
    alert("hello"); 
}

i.test();

I expect the code to alert 'hello', but instead, the Firefox error console shows:

missing } in XML expression
alert("hello"); 
---------------^

How do I fix this...

+4  A: 

Your i isn't assigned to anything so it's not an object. It is, in fact, pointing to the global undefined object which happens to be read-only in Firefox (as it should be). You need:

var i = {}; //init to empty object

then all will be fine.

slebetman
I did as you suggested, and all is well. Thanks!
Alterlife
A: 
var i = {};
i.test = function() { 
    alert("hello"); 
};

You had two separate issues. You were not initializing i (as noted by slebetman), and you were missing a semi-colon, forcing the interpreter to use semi-colon replacement.

Matthew Flaschen
A: 

You can't add a function to an undefined value, you need to create an actual object:

var i = {};

Although not required, you should have a semicolon at the end of the statement to avoid ambiguity:

i.test = function() { 
  alert("hello"); 
};
Guffa