比较javascript中的函数指针(Comparing function pointers in javascript)

编程入门 行业动态 更新时间:2024-10-27 02:22:17
比较javascript中的函数指针(Comparing function pointers in javascript)

有没有办法在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.

更多推荐

本文发布于:2023-07-18 19:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1164473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   函数   javascript   pointers   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!