向对象添加动态函数
我试图让它工作,但它不起作用:
var i;
i.test = function() {
alert("hello");
}
i.test();
我希望代码发出“hello”警报,但 Firefox 错误控制台显示:
missing } in XML expression
alert("hello");
---------------^
我该如何解决这个问题...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
i
没有分配给任何东西,因此它不是一个对象。事实上,它指向全局undefined
对象,该对象在 Firefox 中恰好是只读的(理应如此)。你需要:那么一切都会好起来的。
Your
i
isn't assigned to anything so it's not an object. It is, in fact, pointing to the globalundefined
object which happens to be read-only in Firefox (as it should be). You need:then all will be fine.
您不能将函数添加到未定义的值,您需要创建一个实际的对象:
虽然不是必需的,但您应该在语句末尾有一个分号以避免歧义:
You can't add a function to an undefined value, you need to create an actual object:
Although not required, you should have a semicolon at the end of the statement to avoid ambiguity:
你有两个不同的问题。您没有初始化
i
(如 slebetman 所指出的),并且您缺少一个分号,迫使解释器使用分号替换。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.