Sto osservando un comportamento strano in IE cercando di chiamare le funzioni in un'altra pagina tramite function.apply().Perché does.apply() non funziona sui limiti del documento in IE?
Ecco un semplice caso di test:
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>
In Firefox e Chrome tutti i metodi di funzionare correttamente.
In IE (testato in 6, 7 e 8) tutti i metodi applyArgs() e remoteApply() funzionano come previsto.
applyArgs() restituisce un errore "oggetto JScript previsto" quando tenta di chiamare apply (test1.html riga 11).
remoteApply() restituisce lo stesso errore "oggetto JScript previsto" quando tenta di chiamare apply (test2.html riga 5).
Il problema è che devo essere in grado di utilizzare apply(). Posso aggirare il problema facendo qualcosa come il meccanismo RemoteApplyCopy(), ma sto cercando di evitarlo. Perché non si applica() funziona?
Se si finisce di copiare il argomenti in un array, ecco un metodo più breve: 'var a = Array.prototype.slice.call (argomenti, 0);' – Blixt
Ho provato a usare slice facendo args.slice(), ma ho ottenuto lo stesso errore. Ho provato comunque a passare attraverso Array.prototype. – Herms
Inoltre, penso che dovrei farlo nel test2.html. Sto cercando di evitare di avere del codice in più nella pagina di destinazione a tutto (solo le funzioni effettive vengono chiamate). – Herms