我在IE中看到一些奇怪的行爲,試圖通過function.apply()調用另一個頁面中的函數。爲什麼function.apply()在IE中的文檔邊界上工作?
這裏有一個簡單的測試案例:
test1.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
var opened = null;
function applyNone() {
opened.testFunc.apply(opened);
}
function applyArgs() {
opened.testFunc.apply(opened, ["applied array"]);
}
function call() {
opened.testFunc("called directly");
}
function remoteApply() {
opened.testApply(["used remote apply"]);
}
function remoteApplyCopy() {
opened.testApplyCopy(["used remote apply copy"]);
}
function openPopup() {
opened = window.open("test2.html", "_blank");
}
</script>
</HEAD>
<BODY>
<a href="#" onclick="openPopup()">OPEN</a>
<hr>
<a href="#" onclick="applyNone()">applyNone</a>
<a href="#" onclick="applyArgs()">applyArgs</a>
<a href="#" onclick="call()">call</a>
<a href="#" onclick="remoteApply()">remoteApply</a>
<a href="#" onclick="remoteApplyCopy()">remoteApplyCopy</a>
</BODY>
</HTML>
test2.html:
<HTML>
<HEAD>
<script language="javascript" type="text/javascript">
function testApply(args) {
testFunc.apply(this, args);
}
function testApplyCopy(args) {
var a = [];
for(var i = 0; i < args.length; i++) {
a.push(args[i]);
}
testFunc.apply(this, a);
}
function testFunc() {
var s = "Got: ";
for(var i = 0; i < arguments.length; i++) {
s += arguments[i] + " ";
}
document.getElementById("output").innerHTML += s + "<BR>";
}
</script>
</HEAD>
<BODY>
Hi there
<div id="output"/>
</BODY>
</HTML>
在火狐和Chrome的所有方法的正常工作。
在IE(測試6,7和8)中,除了applyArgs()和remoteApply()方法外,其他所有方法都按預期工作。
applyArgs()在嘗試調用apply(test1.html第11行)時會給出一個「JScript對象預期」錯誤。
remoteApply()在嘗試調用apply(test2.html第5行)時給出了相同的「JScript對象預期」錯誤。
問題是,我需要能夠使用apply()。我可以通過做類似remoteApplyCopy()的機制來解決問題,但我試圖避免這種情況。爲什麼不適用()只是工作?
如果最終複製參數到一個數組中,這裏是一個較短的方法:`var a = Array.prototype.slice.call(arguments,0);` – Blixt 2009-07-10 08:45:31
我嘗試使用切片做args.slice(),但得到了同樣的錯誤。儘管試過了Array.prototype – Herms 2009-07-10 13:39:36
另外,我想我必須在test2.html中這樣做,我試圖避免在目標頁面有任何額外的代碼所有(僅僅是被調用的實際功能)。 – Herms 2009-07-10 13:42:43