自动执行 javascript 函数并稍后调用它们?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10703962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Auto-execute javascript functions AND call them later?
提问by Willy
I read on many places that you can auto launch js functions on load by doing :
我在很多地方都读到过,您可以通过以下方式在加载时自动启动 js 函数:
$(function() {
// code...
});
Or
或者
var myFunc = function() {
// code...
}();
My question is, how do you call these functions later ? Because the simple declaration
我的问题是,你以后如何调用这些函数?因为简单的声明
function myFunc() {
// code...
}
can be easily recalled but doesn't auto-launch. I have to manually call them all on load, and that's annoying, take up spaces in the code and it can be an error source if i forgot one.
可以轻松调用,但不会自动启动。我必须在加载时手动调用它们,这很烦人,占用代码中的空格,如果我忘记了,它可能是一个错误源。
If you don't understand my explanations, here's an example :
如果你不明白我的解释,这里有一个例子:
I have a "weight" and a "height" field in my form, and i need to calculate the BMI (Body Mass Index). When the page loads, the weight and height are filled by the database, then i launch the calculation when everything's ready. But later, if the user changes the weight or the height, the BMI have to recalculate immediately. What's the best way to do that ? Using jquery or pure JS, I don't mind.
我的表单中有一个“体重”和一个“身高”字段,我需要计算 BMI(身体质量指数)。当页面加载时,重量和高度由数据库填充,然后我在一切准备就绪后启动计算。但后来,如果用户改变体重或身高,BMI 必须立即重新计算。最好的方法是什么?使用 jquery 或纯 JS,我不介意。
Thanks.
谢谢。
回答by Joseph
var reference = (function thename(){
//function body
return thename; //return the function itself to reference
}()); //auto-run
reference(); //call it again
reference(); //and again
Note that calling the function returns a reference to the function you just called.
请注意,调用该函数会返回对您刚刚调用的函数的引用。
var anotherReference = reference(); //anotherReference === reference