有没有办法在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();Is there any way to comparing function pointers in javascript? Basically, I want to see if I've added the same function multiple times to an array, and then only add it once. Yeah, I can program my way around it, but it would be much easier to do it this way.
The code below does NOT use an array, but illustrates the point I'm trying to make. I'd like for oldPointer to only be set if a myPointer is a different function.
Here is some example code:
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.Loaded.bind(this)将在每次调用时生成一个新函数。 这就是你的代码不起作用的原因。 不幸的是没有办法引用this.Loaded从bind()生成的函数对象,所以比较是不可能的。
如果你做了类似下面的事情,你的检查会有效,但我不确定它对你有多大用处。
test.prototype.run = function() { var loadedFn = this.Loaded.bind(this); this.Add(loadedFn); this.Add(loadedFn); }如果您想要更好的答案,请详细说明您要做的事情。
Assuming bind is a function that uses Function.apply() to create a function closure binding this to the context, this.Loaded.bind(this) will produce a new function every time it is called. That is why your code does not work. Unfortunately there is no way to reference this.Loaded from the function object produced by bind(), so comparison is impossible.
If instead you did something like the below, your check would work, though I'm not sure how much use it would be to you.
test.prototype.run = function() { var loadedFn = this.Loaded.bind(this); this.Add(loadedFn); this.Add(loadedFn); }Please clarify exactly what you are trying to do if you want a better answer.
更多推荐
发布评论