繁体   English   中英

NodeJS - 从另一个嵌套 Function 内部调用嵌套 Function

[英]NodeJS - Call Nested Function from inside another nested Function

我有两个嵌套函数,我想在第一个函数中调用第二个函数,但我的 nodejs 似乎无法识别它。

function Main(){
  this.NestedA = function(){
    console.log('Hello from A')
  }

  this.NestedB = function(){
    console.log('Hello from B')

    /* How to call NestedA from here? */
    /**
     * I tried
     * NestedA()
     * this.NestedA()
     */
  }
}

我认为你不应该使用this 试试这个方法:

function Main(){
  const NestedA = function() {
    console.log('Hello from A')
  }

  const NestedB = function() {
    console.log('Hello from B');
    NestedA();
  }
}

这是什么? 真的,你不应该需要this 只需将声明更改为普通的 function 声明,您甚至可以对下面的 NestedC 等函数使用 const 赋值。

function Main(){
  function NestedA(){
    console.log('Hello from A')
  }
  const NestedC= () => {
    console.log('Hello from A')
  }

  function NestedB(){
    console.log('Hello from B')
    NestedA();
  }
}

您也可以返回您要调用的 function,并调用它,例如:

 function Main() {
  this.NestedA = function () {
    console.log("Hello from A");
  };

  return (this.NestedB = function () {
    console.log("Hello from B");
  });
}

Main2()(); //Hello from B

不需要使用this

试试这个片段

function Main(){
  NestedA = function(){
    console.log('Hello from A')
  }

  NestedB = function(){
    console.log('Hello from B')
     NestedA();
  }
NestedB();

}
Main();

调用Main()
Main()调用NestedB()
NestedB( NestedB()调用NestedA()

function Main(){
  var that = this;
  this.NestedA = function() {
    console.log('Hello from A')
  }

  this.NestedB = function() {
    console.log('Hello from B');
    that.NestedA();
  }
}

var m = new Main();
m.NestedB();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM