代码之家  ›  专栏  ›  技术社区  ›  Divide by Zero

将参数传递给匿名函数

  •  0
  • Divide by Zero  · 技术社区  · 6 年前

      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包装器时,我需要向这个匿名函数传递一个参数。 有人能解释一下还是给我看相应的文件?我没找到。

    编辑:

    componentWillMount 方法。我正试图接近道具。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Koenigsberg    6 年前

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

    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 . 如果有疑问,请将上下文保存到变量。