By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,474 Members | 1,283 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,474 IT Pros & Developers. It's quick & easy.

passing object property to DOM PROPERTY (NOT ATTRIBUTE!)

P: 1
This is my problem:

Expand|Select|Wrap|Line Numbers
  1.  
  2. $(document).ready(function(){
  3.  
  4. subClass.prototype = document.createElement( 'div' );
  5. subClass.prototype.constructor = subClass;
  6. function subClass() {
  7.     this.x = 5;
  8.     }
  9.  
  10. var divTested = new subClass;
  11. divTested.id = 'test';
  12.  
  13. alert(divTested.x); // works (result is 5)
  14.  
  15. document.body.appendChild(divTested);
  16.  
  17. $('#test').click(function() {alert(this.x);}); // doesnt work!
  18. $('#test').css({'height': 30, 'width': 50, 'background': 'red'});
  19.  
  20. });
  21.  
Jul 16 '11 #1
Share this Question
Share on Google+
1 Reply


Dormilich
Expert Mod 5K+
P: 8,639
the problem why this.x doesn’t work is inheritance and the scope of your calls.

you have a <div> element, that is shared among all subClass instances (because you put it into the prototype).

when you create a subclass instance (divTested), you create a (primary) property x which is an unique (for that instance) instance property.

later you assign the id property, now is where the inheritance chain hooks in.
- first JS looks if there is (what I called primary property) an instance property named id – there isn’t
- next it looks in the prototype chain for such a property – it finds one in the inherited <div> => end
- if there would have been no such property in the prototype chain, a new (primary) instance property is created

up to line 14 no problems.

then it starts to go wrong. appendChild() expects a DOM Node to be given. divTested ain’t one, but it contains one in it’s inheritance chain so I assume, it uses the inherited <div> to insert into the document. that obviously drops everything related to the subClass instance.

next problem at line 17. you access the <div> element. as the <div> element is in the inhertance chain above the subClass instance, it has no knowledge of the x property of the subClass instance and thus you get undefined.
Jul 16 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.