I'm debugging a web application. Javasript in one window create one object and use it as argument to invoke global method in another window. Pseudo code is like below.
var obj = new Foo();
anotherWin.bar(obj);
In anotherWin, the argument is stored in global variable.
var g_obj;
function bar(obj)
{
g_obj = obj;
...
}
开发者_C百科When other function tries to reference g_obj.Id, it throws exception "Cannot evaluate expression". This happens in IE8.0.7600.16385 on Windows 7.
In Visual Studio debugger, when this exception happens, the g_obj shows as
{...}
It looks all its properties are lost.
Perhaps the root reason is the object is created in one window but only referenced in another window. The object might be garbage-collected at any time.
Is there any way to work around this?
DOM objects do not persist across windows. However, if you can live with JSON representation, then I'd convert your object to JSON, send it across and then parse the JSON.
There are several ways to encode and decode JSON in javascript (hint: using eval()
is a security disaster).
- Some modern browsers (Firefox >= 3.5, Internet Explorer >= 8.0) provide secure, fast native implementations.
- Some javascript frameworks (e.g. YUI but not jquery) from the same functionality.
- The most reliable way to do this is use Douglas Crockford's
json2.js
library It is standard's compliant, secure, backwards compatible and will use the browser's native parser if it exists.
Using Crockford's library, your example would become:
<script type="text/javascript" src="json2.js"></script>
[...]
var obj = new Foo();
anotherWin.json_bar(JSON.stringify(obj));
In anotherWin:
<script type="text/javascript" src="json2.js"></script>
[...]
var g_obj;
function bar(obj)
{
g_obj = obj;
[...]
}
function json_bar(json_obj)
{
bar(JSON.parse(json_obj));
}
Don't forget to minify json2.js
- with conservative minification, it is only a 3.5KB hit to your page load size.
is this a one-way operation, or do you want changes made in anotherWin to be reflected in the source window?
if it's one way, i'd convert it to a json string, send it over, and parse it back into an object.
passing a reference may not be doable.
Serialize your object, send it over, then de-serialize it.
精彩评论