我如何将回调传递给函数,然后该函数使用 callee
需要的原始参数调用回调(但用结果替换第一个参数)?
我有这个例子:
this.createImage: function(base64, callback) {
var img = new Image();
img.src = base64;
img.onLoad = function() {
callback(this); // I also want to pass position here (this + arbitrary number of arguments)
}
}
this.addToCanvas: function(item, position) {
if(!this.isImage(item)) { // assume `isImage()` check if item is Image, & skips if true
var item = this.createImage(item, this.addToCanvas);
return;
}
item.position = position;
// Supposedly here I am certain that image is an Image() and not a
// base64 string
}
所以基本上我想知道如何让 createImage
回调 addToCanvas
而不是传递原始 position
但 item
代替加载的 img
。
这里的想法是能够使用 Image
或 base64 String
调用 addToCanvas()
并且仍然能够转换在内部如果需要。
但是,我仍然希望能够将 createImage()
与其他需要使用另一个(任意)数量的参数回调的函数重用。我想知道是否可以将上述功能结合在一起。
最佳答案
我建议只使用本地函数。
如果数据已经是图像,您只需立即调用本地函数来处理它。如果它还不是图像,则将其转换为图像,然后从回调中调用本地函数。
因为局部函数可以访问传递给原始函数调用的所有参数,这解决了您的那部分问题,而无需进行任何特殊参数传递。这也是 Javascript 的一大特色(函数可以访问其所有父参数):
this.createImage = function (base64, callback) {
var img = new Image();
img.onLoad = function () {
callback(img);
}
img.src = base64;
}
this.addToCanvas = function (item, position) {
function addIt(img) {
// we know that img is an actual image here so you can process it now
img.position = position;
// other processing of the image here ...
}
if (!this.isImage(item)) {
// have to make it an image before addIt
this.createImage(item, addIt);
} else {
// already an image, can call addIt now
addIt(item);
}
}
关于javascript - 函数中的拾取参数和带有原始参数的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074367/