首页 > 解决方案 > 无法访问正确的“this”

问题描述

我在我的应用程序中使用 openlayers。一段代码如下:

this.raster = new RasterSource({
  sources: [imageSource],
  operation: (pixels, data) => {
    const pixel = pixels[0]
    this.imageprocessingUtility.adjustPixelChannels(pixel, this.newImageBrightness)
    return pixel
  }
})

imageprocessingUtility 是封闭类的成员。

但在运行时,imageprocessingUtility 是不受限制的。看来“这”不是我所期望的。

这里缺少什么?

资料来源:

https://openlayers.org/en/latest/apidoc/module-ol_source_Raster-RasterSource.html

https://openlayers.org/en/latest/examples/color-manipulation.html

修改后的代码:

var that = this
this.raster = new RasterSource({
  sources: [imageSource],
  operation: (pixels, data) => {
    const pixel = pixels[0]
    that.imageprocessingUtility.adjustPixelChannels(pixel, that.newImageBrightness)
    return pixel
  }
})

错误:

未捕获的 ReferenceError:未定义

在调试过程中,我观察到我的代码被打包成以下代码:

我的代码在最后添加。

var __minion__ = (function createMinion(operation) {
var workerHasImageData = true;
try {
  new ImageData(10, 10);
} catch (_) {
workerHasImageData = false;
}

function newWorkerImageData(data, width, height) {
if (workerHasImageData) {
  return new ImageData(data, width, height);
} else {
  return {data: data, width: width, height: height};
}
}

return function(data) {
// bracket notation for minification support
var buffers = data['buffers'];
var meta = data['meta'];
var imageOps = data['imageOps'];
var width = data['width'];
var height = data['height'];

var numBuffers = buffers.length;
var numBytes = buffers[0].byteLength;
var output, b;

if (imageOps) {
  var images = new Array(numBuffers);
  for (b = 0; b < numBuffers; ++b) {
    images[b] = newWorkerImageData(
        new Uint8ClampedArray(buffers[b]), width, height);
  }
  output = operation(images, meta).data;
} else {
  output = new Uint8ClampedArray(numBytes);
  var arrays = new Array(numBuffers);
  var pixels = new Array(numBuffers);
  for (b = 0; b < numBuffers; ++b) {
    arrays[b] = new Uint8ClampedArray(buffers[b]);
    pixels[b] = [0, 0, 0, 0];
  }
  for (var i = 0; i < numBytes; i += 4) {
    for (var j = 0; j < numBuffers; ++j) {
      var array = arrays[j];
      pixels[j][0] = array[i];
      pixels[j][1] = array[i + 1];
      pixels[j][2] = array[i + 2];
      pixels[j][3] = array[i + 3];
    }
    var pixel = operation(pixels, meta);
    output[i] = pixel[0];
    output[i + 1] = pixel[1];
    output[i + 2] = pixel[2];
    output[i + 3] = pixel[3];
  }
}
return output.buffer;
};
})((pixels, data) => {
    const pixel = pixels[0]
    that.imageprocessingUtility.adjustPixelChannels(pixel, 
    that.newImageBrightness)
    return pixel
  });self.addEventListener("message", function(event) {  var buffer = 
__minion__(event.data);  self.postMessage({buffer: buffer, meta: 
 event.data.meta}, [buffer]);});

标签: javascriptopenlayers

解决方案


推荐阅读