对象中的函数指针 [英] Function pointers in objects
问题描述
我有一个javascript函数,它将一个对象作为参数。我希望传递对象的一个属性是一个函数指针。但该功能已执行,我不想发生。
I have a javascript function that takes an object as a parameter. I want one of the properties of passed object to be a function pointer. But the function is executed which I don't want to happen.
示例:
var myFuncPtr = function(){alert("Done");};
function myFunc(o){
// do something with passed object
// then call the function pointed at in the passed object
}
myFunc( {foo:"bar", onDone: myFuncPtr} );
我确信有专家可以指导我朝着正确的方向前进。我是以错误的方式来做这件事的。如果有快速解决方案,则首选。
I'm sure there's an expert out there who can guide me in the right direction. Am I going about this the wrong way. The quick solution is preferred if there is one.
以下是实际代码:
$(document).ready(function() {
imageCropper({
id:"imageBox",
editWidth:400,
cropWidth:0,
maxFileSize:3000000,
croppedId:"croppedBox",
onCrop:whenImageCropped
});
});
function whenImageCropped(o)
{
alert("done");
}
function imageCropper(options)
{
divId = options.id;
croppedDivId = (options.croppedId)?options.croppedId:divId+"_croppedPic";
$("#"+divId).load("/modules/imageCropper.asp", options, function(){
/* if i remove this bit, then no probs */
$("#"+divId+"_imgToCrop").Jcrop({
},function(){jcrop_api = this;}
);
/* end of - if i remove this bit, then no probs */
});
}
推荐答案
我希望传递对象的一个属性是一个函数指针。但是执行该功能我不想发生。
I want one of the properties of passed object to be a function pointer. But the function is executed which I don't want to happen.
这听起来不是传递对函数的引用,而是正在执行该函数并传递返回值。
That sounds like instead of passing a reference to the function, you are executing the function and passing the return value.
也许在您的原始代码中
myFunc( {foo:"bar", onDone: myFuncPtr()} );
调用 myFuncPtr
并指定返回值到 onDone
。
which calls myFuncPtr
and assigns the return value to onDone
.
问题中的代码很好,只需在 o.onDone()
> myFunc 。
The code in the question is fine though, just call o.onDone()
inside myFunc
.
如前所述,没有指针在JavaScript中,它比这简单得多。函数只是数据类型,如字符串,数字,数组等,它们恰好是可调用的。
As already said, there are no pointers in JavaScript, it's much simpler than that. Functions are just data types such as strings, numbers, arrays etc, which happen to be callable.
这篇关于对象中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!