object literal as prototype property

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dezza
    New Member
    • Nov 2006
    • 1

    object literal as prototype property

    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!!

    Code:
    <script language=javascript>
    function my_object(name)
    {
    	this.name=name
    }
    my_object.prototype.dimensions= {w:100,h:100}
    
    
    
    var x = new my_object('car')
    var y = new my_object('bus')
    
    x.dimensions.w=50
    
    alert(x.dimensions.w)  // am expecting this to be 50
    alert(y.dimensions.w) // am expecting this to be 100, inherited from the prototype
    </script>
  • dreaken667
    New Member
    • May 2007
    • 13

    #2
    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.

    Code:
    <script language=javascript>
    function my_object(name)
    {
    	this.name=name
    	this.dimensions= {w:100,h:100}
    }
    
    var x = new my_object('car')
    var y = new my_object('bus')
    
    x.dimensions.w=50
    
    alert(x.dimensions.w)
    alert(y.dimensions.w)
    </script>
    Originally posted by dezza
    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!!

    Code:
    <script language=javascript>
    function my_object(name)
    {
    	this.name=name
    }
    my_object.prototype.dimensions= {w:100,h:100}
    
    
    
    var x = new my_object('car')
    var y = new my_object('bus')
    
    x.dimensions.w=50
    
    alert(x.dimensions.w)  // am expecting this to be 50
    alert(y.dimensions.w) // am expecting this to be 100, inherited from the prototype
    </script>

    Comment

    Working...