按名称调用闭包中的本地函数

Calling local functions in closure by name

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

我有以下代码结构:

(function() {
   var Module = (function() {
      var firstMethod = function() {
         var name = 'secondMethod';
         console.log(window[name]());
      };
      var secondMethod = function() {
         return 2;
      };
      return {
         firstMethod: firstMethod
      };
   })();
   Module.firstMethod();
})();

代码应该返回2,但它返回一个错误,即window[name]未定义,这是真的。

为什么这是未定义的,我该如何解决?

不清楚您想要做什么:您定义了var secondMethod,这使它成为本地的。window用于全局变量。你可以:

window.secondMethod = function() { return 2 }

或:

(function() {
   function Module() {
      this.firstMethod = function() {
         var name = 'secondMethod';
         console.log(this[name]());
      };
      this.secondMethod = function() {
         return 2;
      };
      return this;
   };
   var module = new Module();
   module.firstMethod();
})();
(function () {
    var Module = (function () {
        var firstMethod = function () {
            var name = 'secondMethod';
            console.log(window[name]());
        };
        window.secondMethod = function () {
            return 2;
        };
        return {
            firstMethod: firstMethod
        };
    })();
    Module.firstMethod();
})();