字符串作为参数传递时,jQuery的值变为未定义

时间:2017-05-27 02:34:50

标签: javascript jquery node.js electron

美好的一天,

我正在使用NodeJS和Electron开展宠物项目。它基本上是一个简单的文本编辑器。但是,在尝试将文本区域的值传递给保存到文件之前的函数时,我遇到了一个问题。 特别是当我在另一个模块中调用一个函数时,内容的值变为'undefined'。我怀疑我传递的错误,或者在我进行调用和调用执行之间被覆盖,因为字符串应该通过引用传递。

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.更改参数的顺序,并删除逗号后面的空格。

2 个答案:

答案 0 :(得分:0)

如果你得到了里面的价值,你应该没事。

if(//someConditionMet//)
{
    var contents = $('#txt_Content').val(); //New line
    var otherVar = $('#txt_Other').val();
    console.log('Use:',otherVar.substring(0,9),'...');
    finalContents = otherModule.someFunc(contents, otherVar);
}

答案 1 :(得分:0)

我找到了解决这个问题的方法。我不确定为什么会有所作为,但我在' otherModule'中改变了两件事。 我改变了' const'让'让' 2.我更改了参数的顺序,删除逗号后的空格 新函数标题如下所示:

let someFunc = function(otherVar,contents) {...}

我还更新了调用以匹配新订单(给定):

finalContents = otherModule.someFunc(otherVar,contents);

我希望这有助于将来的某个人!

相关问题