3

我有这个:

var Coords = function(x, y){
        this.x = x;
        this.y = y;
    }

Coords.prototype.toArray = function(){
    return [this.x, this.y];
}

现在我有一个 Coords 对象数组。我想使用 toArray 方法将每个 Coords 实例转换为数组。我可以编写一个循环,但我宁愿使用 $.map,因为它更短且更具可读性。不幸的是,这:

return $.map(coords_array, Coords.prototype.toArray);

根本不起作用。它只是停止执行。问题可能是关于如何独立于任何对象引用方法。在不首先创建实例的情况下指向方法的任何方式?或者将 $.map 与方法一起使用?

感谢您的见解。

编辑:好吧,事实上,它并没有停止执行(这来自另一个问题)而是$.map(coords_array, Coords.prototype.toArray);返回[null,null,null,null,null ...]。我觉得这种行为很奇怪。

4

3 回答 3

1

尝试类似:

return $.map(coords_array, function(val, i) { val.toArray(); });

有关 jQuery 的 map 函数的更多参考,请参阅此处

于 2012-10-07T22:52:51.400 回答
1

显然,$.map不会将上下文(this)设置为当前正在处理的元素(例如$.each)。

您可以使用包装器:

$.map(coords_array, function(coord) { return coord.toArray(); });

或扩展该toArray()方法以也使用第一个参数:

Coords.prototype.toArray = function() {
    var self = this instanceof Coords ? this : arguments[0];
    return [self.x, self.y];
}
于 2012-10-07T23:04:05.270 回答
0

原因是:

> $.map(coords_array, Coords.prototype.toArray);

不能按预期工作是您将函数的引用传递给map,因此当它被调用时,其this关键字未设置为实例并且默认为全局对象(或在 ES5 严格模式下未定义)。你应该能够做到:

$.map(coords_array, function(item, index) {
    Coords.prototype.toArray.call(item);
});

以便将函数this设置为实例。

编辑

见乔丹的回答。

于 2012-10-07T23:25:25.093 回答