1

我正在使用 Javascript 在 MVC中创建一个 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。

4

3 回答 3

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);

于 2018-06-18T11:24:42.097 回答
0

您不能直接调用该函数。您将不得不像这样返回它:

function test() {
  return function executeLot(lot1, lot2) {
    // [...]
  }
}
于 2018-06-18T11:22:54.563 回答
0

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

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);
于 2018-06-18T17:42:28.517 回答