简体   繁体   English

将参数传递给匿名函数

[英]Pass an argument to anonymous function

i try to undestand the scope of this wrapped 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();
    });
  };

I am new to JQuery. 我是JQuery新手。 I need to pass an argument to this anonymous function while using the JQuery wrapper. 我需要在使用JQuery包装器时将参数传递给此匿名函数。 Can somebody explain this or show me corresponding docs? 有人可以解释一下还是给我看相应的文档? I did not find it. 我没找到。

edit: 编辑:

For some context: What i am doing is happening in a React components componentWillMount method. 在某些情况下:我正在做的事情发生在React组件componentWillMount方法中。 And i am trying to access the props. 我正在尝试访问道具。

Make sure the context where you call your function knows of test, otherwise you obviously will not be able to pass something you don't know. 确保调用函数的上下文知道测试,否则显然无法传递您不知道的内容。

Then proceed like this: 然后像这样继续:

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

You can always pass parameters to anonymous functions, but the context where you call them needs to know about these parameters. 您始终可以将参数传递给匿名函数,但是调用它们的上下文需要了解这些参数。 This is also how deferred works: 这也是延期的工作方式:

/** 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

With respect to your edit: 关于您的编辑:

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

Then use 然后使用

self.props

in the anonymous function. 在匿名函数中。

EDIT: I think in your case you don't even need to pass any parameters. 编辑:我认为在您的情况下,您甚至不需要传递任何参数。 All you need is to take care of this . 您所需要做的就是照顾好this When in doubt, save a context to a variable. 如有疑问,请将上下文保存到变量。

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

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