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

object literal as prototype property

P: 1
Hi, having some problems with using object literals when creating properties of a prototype object- no idea why this isn't working s expected - i'm sure i'm just missing something really simple.

Any help greatly appreciated!!

Expand|Select|Wrap|Line Numbers
  1. <script language=javascript>
  2. function my_object(name)
  3. {
  4.     this.name=name
  5. }
  6. my_object.prototype.dimensions= {w:100,h:100}
  7.  
  8.  
  9.  
  10. var x = new my_object('car')
  11. var y = new my_object('bus')
  12.  
  13. x.dimensions.w=50
  14.  
  15. alert(x.dimensions.w)  // am expecting this to be 50
  16. alert(y.dimensions.w) // am expecting this to be 100, inherited from the prototype
  17. </script>
  18.  
Nov 30 '06 #1
Share this Question
Share on Google+
1 Reply


P: 13
You're changing the prototype's dimensions instead of the instance's dimensions on line 13 because you've defined the dimensions property outside your object.

Expand|Select|Wrap|Line Numbers
  1. <script language=javascript>
  2. function my_object(name)
  3. {
  4.     this.name=name
  5.     this.dimensions= {w:100,h:100}
  6. }
  7.  
  8. var x = new my_object('car')
  9. var y = new my_object('bus')
  10.  
  11. x.dimensions.w=50
  12.  
  13. alert(x.dimensions.w)
  14. alert(y.dimensions.w)
  15. </script>
Hi, having some problems with using object literals when creating properties of a prototype object- no idea why this isn't working s expected - i'm sure i'm just missing something really simple.

Any help greatly appreciated!!

Expand|Select|Wrap|Line Numbers
  1. <script language=javascript>
  2. function my_object(name)
  3. {
  4.     this.name=name
  5. }
  6. my_object.prototype.dimensions= {w:100,h:100}
  7.  
  8.  
  9.  
  10. var x = new my_object('car')
  11. var y = new my_object('bus')
  12.  
  13. x.dimensions.w=50
  14.  
  15. alert(x.dimensions.w)  // am expecting this to be 50
  16. alert(y.dimensions.w) // am expecting this to be 100, inherited from the prototype
  17. </script>
  18.  
Mar 17 '08 #2

Post your reply

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