自执行匿名函数并再次调用它

self-executing anonymous functions and call it again

本文关键字:调用 函数 执行      更新时间:2023-09-26

我想做这样的事情:

var build= (function(){
  //my function body     
})();
function test(){
   //somthing then call build
   build() //i want to call build function again in my code
}

我该怎么做?我在angular中尝试了这个:

var buildRoot = (() => {
                $SubNode.get({
                    TypeID: vendorAdminService.NodeType.Category
                }, function(data: vendorAdminService.IGetNodeParameters) {
                    $scope.ProductTree = data.TreeNodeModelItem;
                    $scope.AjaxLoading = false;
                }, function(err) {
                    // alert(err)
                })
        })();
$mdDialog.show(confirm).then(function() {
                $Category.Remove(node.ID)
                buildRoot
            }, function() {
            }); 

但它不起作用。有人能指引我吗??

您需要在IIFE中返回一个函数。如果你的IIF不是琐碎的,并且有很多功能,你也可以考虑使用Reveal模块模式。

var build = (function() {
  var f = function() {
    console.log('hello');
  };
  f();
  return f;
})();
function test() {
  build();
}
test();

只需使用一个命名函数。

IIFE需要返回一个函数,以便以后调用。但是这样就不需要匿名函数了。

function build() {
     //my function body
}

var build = function () {
         //my function body
    };
var build = (function() {
    var init = function() {
        // magic code
    };
    return {
        init: init
    }
}());
function test() {
    build.init()
}
test();

您将所有功能都包含在构建对象中,一旦从该对象中返回它们,就可以立即调用它们。这实际上被称为揭示模块模式

有关更多信息,请阅读此

我发现缺少分号";">

$mdDialog.show(confirm).then(function() {
            $Category.Remove(node.ID);
            buildRoot();
        }, function() {
        });