簡體   English   中英

如何調用“定義”內部的JavaScript函數 - 匿名方法

[英]How to call a JavaScript function that is inside a “define” - anonymous method

如何在同一個JS文件中調用在匿名函數內定義的函數。 這是我的代碼片段。 如何調用_testMethodInside()testMethodOutside()

// Line 1 to 13 is an existing code from ESRI API
    define([
        "dojo/_base/declare",
        "dojo/_base/html"
    ], function (
        declare,
        html
    ) {
        return declare([_WidgetBase, _TemplatedMixin], {
            _testMethodInside: function () {
                return 'success';
            }
        });
    });

//Call above using this function
    function testMethodOutside(){
        //How to call _testMethodInside() function from here
    }

按照Dojo文檔。 define塊定義了一個模塊。 您沒有指定模塊ID(可以顯式傳遞或從文件名推斷),因此我將繼續進行,就像模塊名為my/Example

require(['my/Example'], function(Example) {
   var example = new Example();
   example._testMethodInside(); // here is where you call _testMethodInside
}

關鍵是因為模塊是異步加載的,所以你可以安全地調用它的唯一地方是你傳入的回調函數(AMD) require

使用esri的Web應用程序構建器,您通常可以:

1)將所有代碼放在define / require中2)將其分成兩個模塊

這就是流程的設計應該如何進行,例如:

file1.js:

define([
    "dojo/_base/declare",
    "dojo/_base/html"
], function (
    declare,
    html
) {
    return declare([_WidgetBase, _TemplatedMixin], {
        _testMethodInside: function () {
            return 'success';
        }
    });
});

file2.js:

  require([
        './file1'
  ], function (File1) {

      File1._testMethodInside();
  })

此外,以下划線開頭的方法名稱是指定私有方法的常見設計選擇,因此_testMethodInside應該只由file1調用

如果它應該只是_testMethodInside方法和testMethodOutside函數的testMethodOutside函數,請考慮以下內容:

function sharedFunction() {
    return 'success';
}

function testMethodOutside() {
    sharedFunction();
}

define([
    "dojo/_base/declare",
    "dojo/_base/html"
], function (declare, html) {
    return declare([_WidgetBase, _TemplatedMixin], {
        _testMethodInside: sharedFunction
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM