繁体   English   中英

如何通过定义为函数的变量将对象名称作为参数传递给另一个函数?

[英]How to pass object name as parameter through variable defined as function onto another function?

在我的扩展代码中,我收到一个TypeError,我认为这与我没有成功地将一个对象作为参数从一个函数传递,然后通过定义为函数的变量,然后传递给最终函数有关。

更具体地说,我正在调用变量executeOnce (定义为函数),并将参数options传递给它。 然后,此自执行函数必须将此options参数传递给funB() (即funB(options) ),但是我不认为传递的参数funB()其传递给funB() 因此,错误。

我想念什么?

在下面的代码中,如果我更改funB(options); ,它将起作用funB(options); 到一个字符串(即funB("options"); ),但是我不能这样做,因为在我的扩展代码中,我传入了各种参数。

 const obj = { options: { spam: 4 }, }; function funB(options) { obj[options].spam = 6; // the console log below should print "6" but doesn't } var executeOnce = (function (options) { var executed = false; return function () { if (!executed) { executed = true; funB(options); // the function works if i change this to 'funB('options');' } }; })(); funA('options'); function funA(options) { executeOnce(options); } console.log('= ' + obj.options.spam) 

您在executeOnce上错了,您使用immediate function语法为executeOnce变量构建了一个值(听起来不错),但是executeOnce是一个没有any参数的函数,您可以看到return语句。

var executeOnce = (function (options) { // `options` - does not make sense
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            funB(options);
        }
    };
})();

尝试一下,返回具有options的函数是一个参数。

 var executeOnce = (function () {
    var executed = false;
    return function (options) {
        if (!executed) {
            executed = true;
            funB(options);
        }
    };
})();

  const obj = { options: { spam: 4 }, }; function funB(options) { if(obj[options]==undefined) obj[options]={}; obj[options].spam = 6; } var executeOnce = (function (options) { var executed = false; return function (options) { if (!executed) { executed = true; funB(options); // the function works if i change this to 'funB('options');' } }; })(); funA('optionsA'); function funA(options) { executeOnce(options); } console.log(obj) 

我认为您可能会创建比您需要的功能更多的功能,但这并没有破坏任何功能。 问题似乎是返回的函数(关闭)不了解options ,这可以通过在调用返回的函数时将options作为参数传递来解决。

我给返回的函数命名为newFunc ,还在脚本中添加了print语句,以阐明每一步的情况(这使调试方式更容易。)

 // Main const obj = { options: { spam: 4 } }; funA(obj.options); console.log("finally..."); console.log('obj.options.spam = ' + obj.options.spam); // Functions function funB(options){ console.log("funB got..."); console.log(options); options.spam = 6; console.log("funB set options to..."); console.log(options); } function executeOnce(options){ // context for closure (IIFE) console.log("executeOnce got..."); console.log(options); var executed = false; var newFunc = function(options){ console.log("newFunc got..."); console.log(options); if(!executed){ executed = true; funB(options); } }; return newFunc(options); }; function funA(options){ console.log("funA got..."); console.log(options); executeOnce(options); } 

暂无
暂无

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

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