简体   繁体   English

网页加载后覆盖现有的javascript方法-应该可以吗?

[英]Overwriting existing javascript method after web page has loaded— should be possible?

I have a page which uses various internal corporate javascript files for some functionality. 我有一个页面,其中使用各种内部公司javascript文件来实现某些功能。 These files are minified before we include them on the page. 在将这些文件包含在页面上之前,这些文件已缩小。

After the page loads, in the browser javascript console, I can add methods to the existing internal javascript objects like so : MyCompany.CompanyObject.newMethod = function(){...} and that appears to work fine. 页面加载后,在浏览器JavaScript控制台中,我可以将方法添加到现有的内部javascript对象中,例如: MyCompany.CompanyObject.newMethod = function(){...} ,并且看起来可以正常工作。

Overwriting an existing method isn't working so well. 覆盖现有方法效果不佳。 If I do MyCompany.CompanyObject.existingMethod = function(){...} that appears to take hold, but when we actually call existingMethod it's using the old definition, as defined in our minified javascript files. 如果我执行MyCompany.CompanyObject.existingMethod = function(){...}似乎会成功,但是当我们实际调用existingMethod它使用的是旧的定义,如我们缩小的javascript文件中所定义。

If I set a breakpoint on our minified javascript file where existingMethod lives and (say) fire a jQuery click event on a DOM element to trigger it, the breakpoint stops on the old method definition-- which makes sense, since that's what's in the minified file. 如果我在我们的缩小的javascript文件上设置了一个断点,在其中existingMethod existMethod并(例如)在DOM元素上触发了jQuery click事件以触发该断点,那么该断点将在旧方法定义上停止-这是有道理的,因为这就是缩小后的含义文件。

But should that be happening, given that I redefined existingMethod after the page loaded? 但是考虑到我在页面加载后重新定义了existingMethod ,是否应该这样做? We're not reloading the page after I redefine the method, so it shouldn't be the case my new definition was wiped out. 重新定义方法后,我们不会重新加载页面,因此不应该删除新定义。

I think what I'm doing is possible, and it could be something odd is happening in my specific case, but wanted to see if what I'm trying to do is possible? 我认为我正在做的事情是可能的,在我的特定情况下这可能是奇怪的事情,但是我想看看我正在尝试做的事情是否可能? Any chance there's some strange source caching going on when trying this in a browser console? 在浏览器控制台中尝试此操作时,是否有可能进行一些奇怪的源缓存?

When you overwrite the existing method, you are not changing the method itself, but only the reference to the method and making it point to the new method (so now there are two methods in the memory). 覆盖现有方法时,您并没有更改方法本身,而只是更改了对该方法的引用并使其指向新方法(因此,内存中有两个方法)。

If the code passes a reference to the old method to someone else (say by setting it as an event-handler) then the old method will continue to be called. 如果代码将对旧方法的引用传递给其他人(例如,通过将其设置为事件处理程序),则将继续调用旧方法。

You should look at the stack-trace to see who is calling the old method, and then try to figure out where they got the reference from. 您应该查看堆栈跟踪以查看谁在调用旧方法,然后尝试找出他们从何处获得了引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM