函数中的拾取参数和使用原始参数的回调

Pickup argument in function and callback with original arguments

本文关键字:参数 原始 回调 函数      更新时间:2023-09-26

如何将回调传递给函数,并且该函数使用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


这里的想法是能够使用 Imagebase64 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中,你会这样做:

var that = this; // necessary because this has another vaue inside the wrapper function
var item = this.createImage(item, function(x) {
   return that.addToCanvas(x, position)
});
// here you are passing a wrapper function, that 'waits' for an x to be passed in order to call finally addToCanvas, with x and position.
img.onLoad = function() {
  callback(this);  // this goes into the above's x
}

使用像 underscore.js 这样的函数库同样的事情看起来会更优雅,如下所示:

var item = this.createImage(item, _.partial(this.addToCanvas, _, position));