简体   繁体   中英

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. I need to pass an argument to this anonymous function while using the JQuery wrapper. 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. 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 . When in doubt, save a context to a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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