简体   繁体   English

Javascript 命名的自调用函数

[英]Javascript named, self-calling function

I have a couple bits of code that seem like they could be condensed but I'm not sure how.我有一些代码似乎可以压缩,但我不确定如何压缩。

The code I have is this我的代码是这样的

var checkForUnitReferred = function () {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
};
checkForUnitReferred();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

It basically checks if a checkbox is checked and displays a form, otherwise it hides it.它基本上检查一个复选框是否被选中并显示一个表单,否则它会隐藏它。 What I would rather have is something like this我宁愿拥有这样的东西

var checkForUnitReferred = (function() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

I know this doesn't work but I think something like that would be cleaner.我知道这行不通,但我认为这样的事情会更干净。 Anyone know of a way to accomplish this?有谁知道实现这一目标的方法?

How about this:这个怎么样:

var checkForUnitReferred;

(checkForUnitReferred = function() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(function() {
    checkForUnitReferred();        
});

This is possible because the assignment ( = ) operator returns the value set.这是可能的,因为赋值 ( = ) 运算符返回值集。

Name the function directly rather than create an anonymous one to assign to a variable.直接命名函数而不是创建一个匿名函数来分配给变量。 You may also assign this function as the .change() handler without the extra wrapper function:您也可以将此函数指定为.change()处理程序,而无需额外的包装函数:

(function checkForUnitReferred() {
    $("#LeadForm").toggle($("#Claim_UnitReferredNoNull").is(":checked"));
})();

$("#Claim_UnitReferredNoNull").change(checkForUnitReferred);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM