Connecting Tech Pros Worldwide Forums | Help | Site Map

Extending JavaScript Element "class"

Newbie
 
Join Date: Mar 2008
Posts: 1
#1: Mar 10 '08
Hi everybody,

I am trying to extend the JavaScript's native class Element as below. If I then create two or more distinct objects, assigning values to any of them affects all the objets as if they were referencing one and the same object. However, div1 == div2 throws false. Could anybody explain why is that and how to fix this issue?

Expand|Select|Wrap|Line Numbers
  1. function Div()
  2. {
  3.   //Empty
  4. }
  5.  
  6. Div.prototype = document.createElement("DIV");
  7.  
  8. var div1 = new Div();
  9. var div2 = new Div();
  10.  
  11. div1.style.border = "solid 1px black";
  12. div2.style.border = "dashed 4px red";
  13.  
  14. document.body.appendChild(div1);
  15.  
Thanks!
rnd me's Avatar
Expert
 
Join Date: Jun 2007
Location: Urbana IL
Posts: 411
#2: Mar 10 '08

re: Extending JavaScript Element "class"


Quote:

Originally Posted by bluehtrombone

div1 == div2 throws false.
Could anybody explain why is that and how to fix this issue?

Thanks!



objects are passed by ref, not by value, and because div1 and div2 are different objects, they are not equivalent to javascript.

consider the simplest test case:
Expand|Select|Wrap|Line Numbers
  1.  var a={a:1}
  2.  var b={a:1}
  3.  alert(a==b)
  4.  
it shows false, because objects don't compare like primitives.
Reply