【问题标题】:Execute a function which is located inside another function Javascript执行位于另一个函数 Javascript 中的函数
【发布时间】:2018-06-18 11:17:45
【问题描述】:

我正在 MVC 中使用 Javascript 创建一个 Web 应用程序,其中我有一个如下所示的函数

function test() {
   //this function won't do anything but create a new function inside.
     function executeLot(lot1, lot2) {
       //normal function execution;
     }
}

现在我想调用函数executeLot(1,2) 但我无法调用它,因为它位于test()

如何从测试函数外部调用 executeLot。

【问题讨论】:

  • 您可以通过这种方式轻松实现。 function test() { //this function won't do anything but create a new function inside. executeLot(lot1, lot2); } function executeLot(lot1, lot2) { //normal function execution; }
  • 多解释!你是不是只像简单的方法一样使用这个功能?

标签: javascript function


【解决方案1】:

MVC 平台的最佳方式是基于类模型的系统,而不是全局方法或程序代码。

参见示例:

//////////////////////////////////////////////////////////
// Class Definition ECMA 5 - works on all modern browsers 
//////////////////////////////////////////////////////////

function Test() {

     this.executeLot = function(lot1, lot2) {
       //normal function execution;
       console.log(lot1 + " <> " + lot2)
     }
     
}

//////////////////////////////////
// Make instance from this class
//////////////////////////////////

var myTest = new Test();

//////////////////////////////////
// Call method
//////////////////////////////////
myTest.executeLot(1,1);

【讨论】:

    【解决方案2】:

    您可以返回一个函数并将其分配给一个变量,如下所示:

    function test(){
        return function(arg1,arg2){
            // do your magic here
        }
    }
    
    var executeLoot = test();
    //Call your returned function
    var arg1 = 1;
    var arg2 = 2;
    executeLoot(arg1,arg2);
    

    【讨论】:

      【解决方案3】:

      您不能直接调用该函数。您必须像这样退回它:

      function test() {
        return function executeLot(lot1, lot2) {
          // [...]
        }
      }
      

      【讨论】:

      • 为了上帝的震动 NO NO NO
      • @ManosKounelakis 我假设您在谈论后一个版本?是的,它相当难看,我可能应该删除它。还是你指的是别的东西?
      • 是的,我说的是最新版本
      • 在测试中将 executeLoot 分配给 myFunction
      • 再次检查第二个代码中的测试函数主体
      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 2019-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      相关资源
      最近更新 更多