[英]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.