如何将函数作为参数传递,但不执行“父”函数或使用eval()
?(因为我读过它是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它能工作,但问题是 refreshContactList
在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()
来解决这个问题,但根据我所读的,这并不是最佳实践。我怎样才能在JavaScript中将一个函数作为参数传递?
如何将函数作为参数传递,但不执行“父”函数或使用eval()
?(因为我读过它是不安全的。)
我有这个:
addContact(entityId, refreshContactList());
它能工作,但问题是 refreshContactList
在调用函数时触发,而不是在函数中使用时触发。
我可以使用eval()
来解决这个问题,但根据我所读的,这并不是最佳实践。我怎样才能在JavaScript中将一个函数作为参数传递?
function a(first,second)
{
return (second)(first);
}
a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world
我是一名有用的助手,可以翻译文本。
有时您需要处理事件处理程序,因此需要将事件作为参数传递,大多数现代库如React、Angular可能需要这样做。
我需要在reactjs上使用自定义验证覆盖OnSubmit函数(来自第三方库的函数),我像下面一样同时传递了函数和事件。
原文:
<button className="img-submit" type="button" onClick=
{onSubmit}>Upload Image</button>
我创建了一个新的函数upload
,并将onSubmit
和事件作为参数传递。
<button className="img-submit" type="button" onClick={this.upload.bind(this,event,onSubmit)}>Upload Image</button>
upload(event,fn){
//custom codes are done here
fn(event);
}
const invoke = (callback) => {
callback()
}
invoke(()=>{
console.log("Hello World");
})
// Go through this code and try to understand what I have done.
var hello=(name)=>
{
console.log("Hello",name);
}
let loadScript =(src,callback,name )=>
{
let script = document.createElement('script');
script.src=src;
script.onload = function()
{
console.log("Script Loaded");
}
document.body.appendChild(script);
setTimeout(function()
{
callback(name);
// console.log("hii");
},2000);
}
setTimeout(`loadScript("https://cdn.jsdelivr.net/npm/es-module-shims@1/dist/es-module-shims.min.js",hello,"Gaurav")`,5000);
convertToFunc( "runThis('Micheal')" )
function convertToFunc( str) {
new Function( str )()
}
function runThis( name ){
console.log("Hello", name) // prints Hello Micheal
}
var myJSON =
{
"myFunc1" : function (){
alert("a");
},
"myFunc2" : function (functionParameter){
functionParameter();
}
}
function main(){
myJSON.myFunc2(myJSON.myFunc1);
}
这将打印出 'a'。
以下代码与上述代码具有相同的效果:
var myFunc1 = function (){
alert('a');
}
var myFunc2 = function (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
这也具有以下相同的效果:
function myFunc1(){
alert('a');
}
function myFunc2 (functionParameter){
functionParameter();
}
function main(){
myFunc2(myFunc1);
}
使用类作为对象原型的面向对象范例:
function Class(){
this.myFunc1 = function(msg){
alert(msg);
}
this.myFunc2 = function(callBackParameter){
callBackParameter('message');
}
}
function main(){
var myClass = new Class();
myClass.myFunc2(myClass.myFunc1);
}