Javascript工人失去属性

时间:2014-01-28 14:56:10

标签: javascript prototype cluster-analysis web-worker

我正在开发一个webApp,它在地图上显示群集闪电事件(因此一个巨大的群集就像一个雷暴形成)。

为了避免“冻结”用户界面,我正在使用Javascript Worker来执行群集。算法结束时会出现问题,因为它会在我将其发送到主页后返回一个“丢失”某些属性的自定义对象:

//inside Worker.js
var cluster = new DBSCAN(e.data.params).run();
self.postMessage({"cluster": cluster});

集群对象基本上是 GeoPoint 对象的数组,因此:

cluster[0]

是像这样的GeoPoint对象

function GeoPoint(lat, lng){
    this.lat_ = lat;
    this.lng_ = lng;
}
GeoPoint.prototype.lat = function(){ return this.lat_;}
GeoPoint.prototype.lng = function(){ return this.lng_;}

当我使用self.postMessage发送此对象时,我丢失了lat()lng()函数,我需要来绘制多边形。 lat_lng_属性完整无缺。

我能做些什么来克服这个问题?现在我只是循环结果并重建GeoPoint个对象,它可以工作,但看起来很糟糕。

感谢您的任何建议!

编辑:我需要这些函数,因为绘图代码将在lat lon点上执行排序,然后才能计算凸包。

2 个答案:

答案 0 :(得分:0)

根据文档,postMessage使用结构化克隆算法。函数和原型不会转移:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm?redirectlocale=en-US&redirectslug=Web%2FGuide%2FDOM%2FThe_structured_clone_algorithm

收到数据后可以尝试的是更改收到的对象的原型:

worker.onmessage = function(event) {
    var data = event.data;
    data.forEach(function(p) {
        p.__proto__ = GeoPoint.prototype; // That seems to work, but I'm really not sure if this is standard and compatible with all browsers !
    });
};

答案 1 :(得分:0)

  

我能做些什么来克服这个问题?

没有 - postMessage使用的cloning algorithm不会传输原型和函数。在另一方重建它们是必要的。

  

现在我只是简单地循环结果并重建GeoPoint对象,但它看起来非常糟糕。

不,这就是需要做的事情:

var newCluster = messageData.cluster.map(function(likeapoint) {
    var point = new GeoPoint();
    for (p in likeapoint)        // maybe a static list of copied property names
        point[p] = likeapoint[p];// is faster, but not as flexible
    return point;
})

// since all properties are settable as arguments in this specific case:
var newCluster = messageData.cluster.map(function(likeapoint) {
    return new GeoPoint(likeapoint.lat_, likeapoint.long_);
})
相关问题