Alterlife
Alterlife

Reputation: 6625

Adding a dynamic function to an object

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...

Upvotes: 0

Views: 321

Answers (3)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

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.

Upvotes: 0

Guffa
Guffa

Reputation: 700262

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"); 
};

Upvotes: 0

slebetman
slebetman

Reputation: 113866

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.

Upvotes: 4

Related Questions