Javascript自执行功能“不是一个功能”。 [英] Javascript self executing function "is not a function"
问题描述
我有:
var Init = (function() {
my js goes here
})();
我的js在加载页面时正确执行。我还有:
And my js executes correctly when the page is loaded. I also have:
$('form :checkbox').change(function() {
Init();
});
但是firebug说Init不是函数。
But firebug says Init is not a function.
推荐答案
这不是一个函数。
(function() {
...
})()
评估匿名函数那么。在这种情况下,评估的结果显然不会返回函数对象: - )
evaluates the anonymous function right then. And the result of the evaluation apparently does not return a function-object in this case :-)
考虑:
f = (function() {
return "not a function :("
})()
alert(f())
和
f = (function() {
return function () { return "Yay!" }
})()
alert(f())
快乐编码:)
这是一个执行一次然后返回稍后要执行的东西的函数。 (参见你可以[分配]一个功能或者调用它;你不能同时做两个......来自Slaks的答案。)但是,我不会这样做。
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.
Init = (function () {
function Init () {
alert("whee!")
}
Init()
return Init
})()
Init()
这是CD Sanchez的另一个解决方案(更短/更清洁)(见注释),它利用了一个赋值评估指定值的事实:
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:
var Init; (Init = function Init () {
alert ("wee");
})()
这篇关于Javascript自执行功能“不是一个功能”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!