按需覆盖 Javascript 函数变量

发布于 2025-01-06 00:44:03 字数 577 浏览 1 评论 0原文

我的问题与能够覆盖函数中声明的变量有关,但不能覆盖函数中的每次调用。这是我的解释:

假设页面加载时我有三个 HTML 元素:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

然后我运行一个 javascript 函数来操作每个元素并将函数应用于“onmousemove”事件。在函数调用期间,声明了一些变量,不应覆盖这些变量,以保持变量值对于元素是唯一的(否则鼠标移动将被覆盖并且仅适用于最后一个元素)。我知道这可以通过声明它们局部变量来实现。

我的问题是下一部分:

完成这一切后,页面上会发生其他事件,这些事件会触发初始函数在最初运行的同一元素上再次运行,但具有不同的值,现在必须覆盖原件。我会发布代码,但它有几千行代码,所以我希望你们都明白我在说什么。

我认为我可以通过复制函数并以不同的方式声明变量来解决这个问题,但这意味着拥有一大段代码的两个副本,在我看来,这从来都不是一个好主意,我想避免这种情况。

My problem has to do with being able to overwrite the variables declared within a function but not on every recall on the function. Here is my explanation:

Let's say I have three HTML elements when the page is loaded:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

I then run a javascript function manipulating each of these elements and applying functions to the "onmousemove" event. During the function call there are variable that are declared and should NOT be overwritten in order to keep the variable values unique to the element (otherwise mouse movement would be overwritten and would only work for the last element). I know this can be achieved by declaring them local variables.

My issue is the next part:

After this has all been done, I then have other events on the page that trigger the initial function to run again on the same element it ran on initially, but with different values, which now have to overwrite the originals. I would post the code but it is a few thousand lines of code so I'm hoping you all understand what I'm talking about.

I think I can fix this issue by duplicating the function and declaring the variables differently, but that would mean having two copies of a large block of code, which is never a good idea, in my opinion and I would like to avoid that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终弃我 2025-01-13 00:44:03

所以我想出了如何实现我想要的。我将代码重新设计成对象。当我最初运行代码时,每个元素都有自己的对象,其中包含一个可变全局变量 (window[element+'obj']),该对象使用原型方法操作元素,这使每个元素值保持独立,然后当我需要覆盖对于特定元素,我调用一个方法来重置该对象的所有值。稍后我将尝试为遇到此问题的任何人发布一些示例代码。

谢谢!

So I figured out how to achieve what I wanted. I reworked my code into Objects. When I run the code initially each element has its own object with a variable global variable (window[element+'obj']) that manipulates the element with prototype methods, which keeps each elements values separate, then when I need to overwrite the values for a particular element, I call a method that resets all the values for that object. I will try to post some example code later for anyone that runs into this issue.

Thanks!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文