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>
firefox と chrome では、すべてのメソッドが適切に機能します。
IE (6、7、および 8 でテスト済み) では、applyArgs() メソッドと remoteApply() メソッドを除くすべてが期待どおりに機能します。
applyArgs() が apply を呼び出そうとすると、「JScript オブジェクトが必要です」というエラーが発生します (test1.html の 11 行目)。
remoteApply() は、apply を呼び出そうとすると、同じ「JScript オブジェクトが必要です」というエラーを返します (test2.html の 5 行目)。
問題は、apply() を使用できるようにする必要があることです。remoteApplyCopy() メカニズムなどを実行することで問題を回避できますが、それを回避しようとしています。apply() が機能しないのはなぜですか?