Javascript:非法调用 [英] Javascript: Illegal invocation
问题描述
我遇到了一个问题.我正在使用一个具有以下逻辑的相当老的应用程序:
I am experiencing an issue. I am working with a fairly old application which has the following logic:
var Page;
var OriginalSubmit;
function init() {
Page = document.forms[0];
OriginalSubmit = Page.submit;
Page.submit = newPageSubmit;
}
function newPageSubmit() {
validate();
OriginalSubmit();
}
当执行OriginalSubmit时,我得到一个非法调用参数.我已经读够了,这是因为此引用已更改(至少我认为是这种情况),但是我正在努力解决的是正确的方法.为此,JavaScript很混乱,到处都是JSP和全局函数,因此要使其正确将是一项艰巨的工作,因此,我很想看看是否有可能采用侵入性较小的解决方案,谢谢.
When the OriginalSubmit is executed, I get an Illegal invocation argument. I've read enough to understand that is because the this reference has changed (at least I think that's the case), but what I am struggling with is the correct way to fix it. The JavaScript for this is a mess, wrapped up with JSPs and global functions everywhere, so making this correct would be quite an effort, so I am looing to see if there's a chance for a less invasive solution, thanks.
推荐答案
分配OriginalSubmit = Page.submit
时,您会获得对.submit()
函数的引用,但是当您将其仅作为普通OriginalSubmit()
调用时,丢失Page
上下文变量,该上下文变量将作为this
传递给该函数:
When you assign OriginalSubmit = Page.submit
you're obtaining a reference to the .submit()
function, but when you call it as just plain OriginalSubmit()
you're losing the Page
context variable that will be passed as this
to that function:
myObject.method(); // calls "method" with "this === myObject"
var method = myObject.method();
method(); // calls "method" with "this === window"
相反,请使用:
OriginalSubmit.call(Page); // sets "this" to "Page"
请注意,即使那样,重新分配本机DOM元素的方法也可能无法在所有浏览器中移植,并且可能根本无法使用.
Note that even then, it's possible that re-assigning a method of a native DOM element won't work portably in all browsers, and may not work at all.
这篇关于Javascript:非法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!