繁体   English   中英

将参数传递给匿名函数

[英]Pass an argument to anonymous function

我试图不理解这个包装功能的范围。

  componentWillMount = () => {
    //-----------------------
    // props accesible here:
    //-----------------------
    console.log(this.props);
    $(function() {
      var jqconsole = $('#console').jqconsole('Welcome to the console!\n', '>');
      jqconsole.Write(
        //-----------------------
        // props inaccesible here:
        //-----------------------
        this.getMessagesFromJavascriptWindow(this.props.code) + '\n',
        'jqconsole-output'
      );
      var startPrompt = function() {
        // Start the prompt with history enabled.
        jqconsole.Prompt(true, function(input) {
          let transformedString;
          try {
            transformedString = eval(input);
            // Output input with the class jqconsole-output.
            jqconsole.Write(transformedString + '\n', 'jqconsole-output');
            // Restart the input prompt.
            startPrompt();
          } catch (error) {
            jqconsole.Write(error + '\n', 'jqconsole-output-error');
            // Restart the input prompt.
            startPrompt();
          }
        });
      };
      // Restart the input prompt.
      startPrompt();
    });
  };

我是JQuery新手。 我需要在使用JQuery包装器时将参数传递给此匿名函数。 有人可以解释一下还是给我看相应的文档? 我没找到。

编辑:

在某些情况下:我正在做的事情发生在React组件componentWillMount方法中。 我正在尝试访问道具。

确保调用函数的上下文知道测试,否则显然无法传递您不知道的内容。

然后像这样继续:

var self = this;
$(function( self ){ can access this.props here via self.props })

您始终可以将参数传递给匿名函数,但是调用它们的上下文需要了解这些参数。 这也是延期的工作方式:

/** define in some context */
var dfd = $.Deferred();
dfd.resolve( 5 );

/** define in some other context, that knows of the dfd above */
dfd.done( function ( param ) { console.log( param ); });

// result: 5

关于您的编辑:

var self = this; // before calling the anonymous function

然后使用

self.props

在匿名函数中。

编辑:我认为在您的情况下,您甚至不需要传递任何参数。 您所需要做的就是照顾好this 如有疑问,请将上下文保存到变量。

暂无
暂无

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

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