簡體   English   中英

從module.export調用; 相同模塊內的功能

[英]Call from module.export ; a function that is inside the same module.export

我需要有關這段代碼的幫助。 我正在嘗試做的是在module.export的“根”中調用一個函數。 但是調用是從同一module.export內部的函數提供的。 這是我得到的:

從另一個腳本中,我調用了“ base-execute”函數。 我正在嘗試做的是在此之后立即調用函數“ Tocall-Function”。 這可能嗎 ?

module.exports.main = {

   Part1 : {
      Sub1 : {
         base-execute(){
           // Some code and then call the "Tocall-Function" //
         }
      },
      Sub2 : {...}
   },
  Part2 : {...}


  Tocall-Function(){
    //Another piece of code//
  }

} 

我嘗試了'this.Tocall-Function'。 但是,“ this”本身僅返回“ base-execute”函數之前的內容(Sub1部分內部的內容)。

我可以訪問不在module.exports.main內部的變量。 但是我不能自己稱呼它。

我找不到適合我的情況的東西。 如果有人可以幫助我,那就太好了!

感謝您的閱讀。

您可以將main與export分開定義,並使用main.TocallFunction();調用要調用的函數main.TocallFunction();

const main = {

  Part1 : {
    Sub1 : {
      baseExecute() {
        main.TocallFunction();
        // Some code and then call the "Tocall-Function" //
      }
    },
    Sub2 : {}
  },
  Part2 : {},
  TocallFunction() {
    //Another piece of code//
  }
};

exports.main = main;

一種簡單的解決方法是從腳本中創建對導出對象的引用。

var main = {

   Part1 : {
      Sub1 : {
         base-execute(){
           // Some code and then call the "Tocall-Function" //

           main.Tocall_Function()
         }
      },
      Sub2 : {...}
   },
  Part2 : {...}


  Tocall_Function(){
    //Another piece of code//
  }

} 


module.exports.main = main;

讓我們嘗試一下:


    const toCallFunction = () => console.log("To Call Function");

    module.exports = { toCallFunction: toCallFunction, main: { part1: { sub1: () => toCallFunction  }} };

然后,您可以像這樣導入模塊:

    const { main, toCallFunction } = require("./myCustomModule")

暫無
暫無

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

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