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...
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.
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");
};
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.
精彩评论