javascript - 将参数传递给匿名函数
问题描述
我试图理解这个包装函数的范围。
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 })
您始终可以将参数传递给匿名函数,但调用它们的上下文需要了解这些参数。这也是 deferred 的工作方式:
/** 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
。如有疑问,请将上下文保存到变量中。
推荐阅读
- node.js - NodeJS 无法进行身份验证,即使我提供了不记名令牌
- php - URL 重写以在我的 Nginx PHP-FPM 中删除 .php
- flutter - 有没有办法在列表视图构建器中为每个容器添加不同的图像?
- linux - How to combine two ffmpeg bin script into one script
- variables - Ansible registered variable has attribute not found error due to multiple when conditions
- android - 我可以在 Flutter 中使用 GestureDetectors 从本机平台检测手势吗
- c# - Environment variable set in base test class is not available in derived test classes
- python - How to draw bounding boxes on ROI using opencv
- solr - Solr 增加 maxBooleanClauses 不起作用
- android - 在 Kotlin 的 Data 类中拥有内部类和接口是否是最佳实践