【问题标题】:Comparing a static functions equality in javascript?比较javascript中的静态函数相等性?
【发布时间】:2013-04-08 02:57:02
【问题描述】:

我正在处理一个小项目,该项目的其中一个对象可以包括更新函数,该函数被添加到作为对象属性的数组中。

例子,

/*
    Add an update function to the layer
    @param function {update} The update to add
*/
Layer.prototype.addUpdate = function (update) {

    // Add the update
    this.updates.push(update);
};

/*
    Remove an update from the layer
    @param function {update} The update to remove
*/
Layer.prototype.removeUpdate = function (update) {

    this.updates.forEach(function (element, index) {

        if (element.toString() === update.toString()) {
            this.updates.splice(index, 1);
        }
    }, this);
};

通过上面的代码,我可以像这样使用它;

var layer = new Layer();
var func = function () {
     x = 10;
};
layer.addUpdate(func);
layer.removeUpdate(func);

在网上阅读了关于这样做比较函数相等性的信息后,我读到的所有地方都说这样做真的很糟糕。

在函数上使用toString() 真的那么糟糕吗?

在添加和删除更新时只为两个参数提供函数的同时,我还有其他方法可以做到这一点吗?

UDPATE

有没有办法检查两个变量是否指向同一个引用?示例(伪);

var a = 10;
var b = a;
var c = a;

if (b and c point to a) //

【问题讨论】:

  • toString 在存在不同 cmet 的情况下将不起作用

标签: javascript function tostring equality


【解决方案1】:

当然。比较函数本身:

if(element === update) {
    // ...

但是,当forEach 循环遍历数组时,您可能会遇到修改数组的问题。

【讨论】:

  • 这只会起作用 Carl 比较完全相同的函数对象,而不是 2 个相同的函数。
  • @ben336:如果它们不是完全相同的函数对象,它们就不是相同的函数。
  • @icktoofay:为什么不呢?您可以使用相同的签名和正文创建 2 个不同的函数。我想这就是本的意思。
  • @Mark:说我 shim bind(很差):Function.prototype.bind = function(thisArg) { var f = this; return function() { return f.apply(thisArg); }; };。现在我绑定两个函数:function a(x) { return x + 1; } function b(x) { return x - 1; } var boundA = a.bind(window); var boundB = b.bind(window);。现在boundAboundB 做了完全不同的事情,但它们的签名和正文是相同的:function() { return f.apply(thisArg); }boundA.toString() === boundB.toString().
  • @CarlG: === 在函数确实比较参考。这就是我的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-26
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多