Javascript 使用";这";从module.exports中的函数调用

Javascript 使用";这";从module.exports中的函数调用,javascript,node.js,scope,this,Javascript,Node.js,Scope,This,我正在从模块内调用本地函数。导出函数。如何访问导出此对象 exports.myVar = 'foo' exports.myFunc = function() { localFunc() } function localFunc() { console.log(this.myVar) //Undefined } 我尝试过使用localFunc().bind(this),但这也不起作用。感谢您的帮助 只需使用导出。或者将myVar声明为变量,将其分配给导出,并在其周围为localFun

我正在从
模块内调用本地函数。导出
函数。如何访问
导出
对象

exports.myVar = 'foo'

exports.myFunc = function() {
  localFunc()
}

function localFunc() {
  console.log(this.myVar) //Undefined
}

我尝试过使用
localFunc().bind(this)
,但这也不起作用。感谢您的帮助

只需使用
导出
。或者将
myVar
声明为变量,将其分配给导出,并在其周围为
localFunc
创建一个闭包


这只在您进行事件绑定和/或创建对象时才有意义。

只需使用
导出即可。或者将
myVar
声明为变量,将其分配给导出,并在其周围为
localFunc
创建一个闭包

这只有在您进行事件绑定和/或创建对象时才有意义。

这就是我所做的:

function localFunc() {
   const self = exports;
   console.log(self.myVar);
}

exports.myVar = 'foo';

exports.myFunc = function () {
    localFunc();
}
我就是这么做的:

function localFunc() {
   const self = exports;
   console.log(self.myVar);
}

exports.myVar = 'foo';

exports.myFunc = function () {
    localFunc();
}
您可以尝试以下方法:

var data = module.exports = {
  myVar: 'foo',

  myFunc: function() {
    localFunc();
  }
}

function localFunc() {
  console.log(data.myVar);
}
您可以尝试以下方法:

var data = module.exports = {
  myVar: 'foo',

  myFunc: function() {
    localFunc();
  }
}

function localFunc() {
  console.log(data.myVar);
}

有两种方法可以解决您的问题

第一:

exports.myVar = 'foo'

exports.myFunc = function() {
  that = this;
  localFunc(that)
}
function localFunc(that) {
  console.log(that.myVar) //foo
}
第二

exports.myVar = 'foo'

exports.myFunc = function() {
  localFunc()
}

localFunc = ()=> {
  console.log(this.myVar) //foo
}

有两种方法可以解决您的问题

第一:

exports.myVar = 'foo'

exports.myFunc = function() {
  that = this;
  localFunc(that)
}
function localFunc(that) {
  console.log(that.myVar) //foo
}
第二

exports.myVar = 'foo'

exports.myFunc = function() {
  localFunc()
}

localFunc = ()=> {
  console.log(this.myVar) //foo
}
bind(this)只返回一个新函数,它是localFunc函数,但它绑定到括号中的任何内容。您需要将新函数(由localFunc.bind返回)实际分配回localFunc。以下是两个简单的例子:

exports.myVar = 'foo';

exports.myFunc = function() {
    localFunc = localFunc.bind(this);
    localFunc();
};

function localFunc() {
    console.log(this.myVar);
}
或:

第二个选项可能比第一个更好,因为在第一个示例中,每次调用exports.myFunc时都必须重新绑定该函数。

localFunc.bind(该选项)只返回一个新函数,即localFunc函数,但该函数绑定到括号中的任何内容。您需要将新函数(由localFunc.bind返回)实际分配回localFunc。以下是两个简单的例子:

exports.myVar = 'foo';

exports.myFunc = function() {
    localFunc = localFunc.bind(this);
    localFunc();
};

function localFunc() {
    console.log(this.myVar);
}
或:


第二个选项可能比第一个更好,因为在第一个示例中,每次调用exports.myFunc时,您都必须重新绑定该函数。

您希望
this
成为什么?我希望
this
成为
foo
何处是
foo
?您的意思是希望
this
成为
导出
?您希望
这个
成为什么?我希望
这个
成为
foo
何处是
foo
?您的意思是希望
成为
导出
localFunc
确实是此模块的私有函数,因此我不希望将其导出。您能提供一个您所指的示例闭包吗?
localFunc
实际上是此模块的私有函数,因此我不希望将其导出。您可以提供一个您所指的示例闭包吗?或者您可以直接使用
exports.myVar
或者直接使用
exports.myVar