将参数传递给匿名函数

驼鹿

我试图理解这个包装函数的范围。

  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方法中。我正在尝试访问道具。

柯尼斯堡

确保您调用函数的上下文知道 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如有疑问,请将上下文保存到变量。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章