【发布时间】:2017-10-27 23:38:30
【问题描述】:
美好的一天,
我正在使用 NodeJS 和 Electron 开发一个宠物项目。目前它基本上是一个简单的文本编辑器。但是,在保存到文件之前尝试将文本区域的值传递给函数时,我遇到了一个问题。 特别是当我在另一个模块中调用函数时,内容的值变为“未定义”。我怀疑我传递它不正确,或者它在我进行调用和调用执行之间被覆盖,因为字符串应该通过引用传递。
Renderer(index.html) 的代码是这样的:
let otherModule = require('./js/otherModule.js');
let $ = require('jquery');
$('#btn_Save').on('click',() => {
// get the fileName, if empty propmt user with save dialog,
//log it to console for debugging
var contents = $('#txt_Content').val();
console.log('with:',contents.substring(0,9),'...');
var finalContents = contents; // (create a copy?)
if(//someConditionMet//)
{
var otherVar = $('#txt_Other').val();
console.log('Use:',otherVar.substring(0,9),'...');
finalContents = otherModule.someFunc(contents, otherVar);
}
//do something with final contents.
})// end of On-click
我已经使用 console.log() 来广泛评估该函数,并且可以确认直到调用 otherModule,内容是正确的,并且与 textArea 中的内容相匹配。一旦我们在“otherModule”中,事情出了差错。
otherModule的代码是这样的:
const someFunc = function(contents, otherVar)
{
console.log('DoThings with:',contents.substring(0,9),'...');
// print shows the value to be undefined...
// do more things
console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
// prints just fine as as expected.
// do more things
return someString;
}
module.exports = {
someFunc: someFunc
}
正如评论中提到的,函数的第一行记录了控制台的内容,控制台将子字符串显示为“未定义”。
感谢您的时间和考虑!
// 额外上下文//
我已经进行了一些搜索,但除了了解字符串是通过引用传递并且是不可变的之外,我还没有看到这样的问题的答案。已经有一些关于闭包问题的讨论,但通常是在事件和回调的上下文中,我认为这不是这里的上下文。
// 额外信息//
我已经找到了让我的参数正确传递的解决方案。我已经在下面发布了答案。我做了两件事: 1.将函数定义从'const'更改为'let' 2. 改变参数的顺序,去掉逗号后面的空格。
【问题讨论】:
标签: javascript jquery node.js electron