E4X assignment gotcha

Obscure TIP Warning

E4X allows direct embedding of XML literals inside JavaScript which make it very easy to work with XML inside JavaScript. Recently while working on a Firefox extension I got bit by some unexpected behavior of an XML variable assignment operator (=). Basically it clones the XML document fragment on the right hand side of assignment operator. The following program demonstrates the behavior.

<html>
<head>
<title>E4X</title>
<script>
function e4x() {
var languages = <languages></languages>;
alert("initial value of variable 'languages'=:\\n" + languages.toXMLString());
var javascript = <scripting>JavaScript</scripting>
alert("initial value of variable 'javascript':\\n" + javascript.toXMLString());
languages.scripting = javascript;
alert("after adding 'javascript' variable as a child node - value of variable 'languages':\\n" + languages.toXMLString());
javascript.version = <version>1.2</version>
alert("after adding version node - value of variable 'javascript':\\n" + javascript.toXMLString());
alert("after adding version node to variable 'javascript' - value of variable 'languages':\\n" +
languages.toXMLString() +
"\\nvalue of variable 'languages' does not reflect the changes made to the value of variable 'javascript'.");
}
</script>
</head>
<body onload="e4x();">
</body>
</html>

You can try this program (if you are using Firefox) by clicking here

 

Comments:

Post a Comment:
Comments are closed for this entry.
About

sandipchitale

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today