Javascript自执行函数“不是函数”
我有:
var Init = (function() {
my js goes here
})();
当页面加载时,我的 js 可以正确执行。我也有:
$('form :checkbox').change(function() {
Init();
});
但是 firebug 说 Init 不是一个函数。
I have:
var Init = (function() {
my js goes here
})();
And my js executes correctly when the page is loaded. I also have:
$('form :checkbox').change(function() {
Init();
});
But firebug says Init is not a function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它不是一个函数。
立即计算匿名函数。在这种情况下,评估结果显然不会返回函数对象:-)
考虑:
并且
快乐编码:)
这是一个函数,它将“执行一次某事”,然后“返回该函数”稍后执行的事情”。 (参见 Slaks 回答中的“您可以[分配]一个函数或调用它;您不能同时执行这两个操作...”。)但是,我不会这样做。
这是 CD Sanchez 的另一个解决方案(更短/更干净)(请参阅评论),它利用了赋值计算为指定值的事实:
It isn't a function.
evaluates the anonymous function right then. And the result of the evaluation apparently does not return a function-object in this case :-)
Consider:
and
Happy coding :)
Here is a function which will "execute something once" and then "return that something to execute later". (See "You can either [assign] a function or call it; you can't do both..." from Slaks answer.) However, I wouldn't do it like this.
Here is another solution (much shorter/cleaner) from CD Sanchez (see comment) which takes advantage of the fact that an assignment evaluates to the assigned value:
为了让
Init
作为函数执行,自执行函数中的代码必须返回一个函数,这样做的唯一原因是如果您需要动态地构造一个依赖于某些函数的特定函数。数据表明:In order for
Init
to execute as a function, your code within the self-executing function must return a function, and the only reason to do this is if you need to construct a specific function dynamically dependent upon some data states:Init
不是一个函数;这是调用函数的结果。您可以创建一个函数或调用它;你不能同时做这两件事。
从技术上讲,您可以通过添加
return argument.callee;
来从调用中返回函数来解决此问题。然而,这是一个愚蠢的想法。
您可能不应该调用该函数;你需要了解你想要你的代码做什么。
Init
isn't a function; it's the result of calling the function.You can either create a function or call it; you can't do both at once.
Technically, you could fix that by adding
return arguments.callee;
to return the function from the call.However, that's a dumb idea.
You probably shouldn't be calling the function; you need to understand what you want your code to do.
快一
尝试像这样替换
并在加载时调用 Init
Quick one
Try replacing like this
and on load call Init
你可以像上面那样做,但你也可以做
没有什么可以阻止你拥有一个命名的自执行函数。
如果您想避免使用名为 Init 的函数,您可以按照 CD Sanchez 的建议进行操作并在执行中分配它。
这 ();最后让它自动执行。将函数括在括号中使其成为匿名函数。但你似乎不希望它是匿名的。
you could do as above, but you could also do
There's nothing to stop you from having a named self-executing function.
If you want to avoid having a function named Init, you can do as CD Sanchez suggested and assign it in the execution.
The (); at the end makes it self executing. Wrapping the function in parentheses makes it anonymous. But it seems that you don't want it to be anonymous.
您可以尝试这样声明它:
但这会减少该函数在其主体中的使用。
其他方法是将声明与执行分开:
You may try declaring it this way:
But this will reduce usage of this function into it's body
Other way is to separate declaration from execution: