比较javascript中的函数指针

Comparing function pointers in javascript

本文关键字:函数 指针 javascript 比较      更新时间:2023-09-26

有什么方法可以比较javascript中的函数指针吗?基本上,我想看看我是否向数组多次添加了相同的函数,然后只添加了一次。是的,我可以用我的方式来编程,但这样做会容易得多。

下面的代码没有使用数组,但说明了我试图表达的观点。我希望只有当myPointer是不同的函数时才能设置oldPointer。

以下是一些示例代码:

function test()
{
}

test.prototype.Loaded = function()
{
   this.loaded = true;
}
test.prototype.Add = function(myPointer)
{
    if (this.oldPointer != myPointer)  //never the same
    {
      this.oldPointer = myPointer;
    }
}
test.prototype.run = function()
{
   this.Add(this.Loaded.bind(this));
   this.Add(this.Loaded.bind(this));  //this.oldPointer shouldn't be reassigned, but it is
}
var mytest = new test();
test.run();

假设bind是一个使用function.apply()创建函数闭包的函数,将this绑定到上下文,则每次调用this.Loaded.bind(this)时都会生成一个新函数。这就是您的代码不起作用的原因。不幸的是,无法从bind()生成的函数对象中引用this.Loaded,因此无法进行比较。

如果你做了下面这样的事情,你的支票会起作用,尽管我不确定它对你有多大用处。

test.prototype.run = function()
{
   var loadedFn = this.Loaded.bind(this);
   this.Add(loadedFn);
   this.Add(loadedFn);
}

如果你想要一个更好的答案,请明确你想做什么。

如果你的问题是"如何有效地避免将同一函数添加到给定的数组中两次?"那么最简单的编程方法显然是:

// Add f to a if and only if it is not already in a
if (a.indexOf(f) < 0) {
    a.push(f);
}

如果indexOf的线性复杂性让你感到困扰,并且你只关心一个数组,你可以非常想象并将函数加载到函数本身的事实存储起来:

// Add f to a if and only if it is not already in a
if (! f.alreadyAddedToA) {
    a.push(f);
    f.alreadyAddedToA = true;
}

为hack属性选择任意名称。

如果你担心多个数组,你可以在函数中存储一种hashmap(JS中被黑客攻击的对象,带有合适的键)。