Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Why's this object not working(Javascript)

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #153887
    javascriptnewbie
    Participant
    box=new Object();
    box.height=30;
    box.length=20;
    
    box.both=function(box.height,box.length){
    return box.height*box.length;
    }
    
    document.write(box.both(10,20));
    

    Well as the title says.

    First off I’d created an object.
    Made to properties, height and length.
    Assigned a value to each.
    Made a method BOTH
    In function I’d put 2 arguments which are object properties.
    Returned their product.
    And finally called the function giving it numerical value..

    Why’s this not working :(

    #153892
    __
    Participant

    You can’t use dot notation in function parameters.

    How are you testing your javascript? Are you using a console? This sort of error is very easy to track down—any console will tell you, explicitly, something like

    SYNTAX ERROR: Unexpected token .

    Beyond that, what are you trying to do?

    Do you want to pass these parameters, or do you want the function to always use the current values of the box properties, automatically?

    var Box = function(){ 
        return { 
            height: 30, 
            length: 20, 
            both: function(){ 
                return this.height + this.length; 
            } 
       }; 
    }
    
    var myBox = new Box(); 
    alert( myBox.both() );
    

    Some tips here:

    1 . instead of building a new object each time, you now have a constructor function Box, that gives you a basic box whenever you need it.

    2 . using this inside the function means you want the height/length properties from this box (and not the default box, or some other box you’ve made).

    3 . I’m using alert in my demo—I’ve seen you use document.write a lot, and you should be aware that it’s not always a good idea. Sometimes it’s fine, sometimes it destroys your document. It is predictable, but you have to learn about it. In the meantime, I highly suggest not making it a habit.

    #153898
    Alen
    Participant
    #153908
    __
    Participant

    That’s a really good video.

    Don’t listen when he calls chapter 6 “Classical” – it’s not really; plus, you shouldn’t be trying to do classical inheritance in JavaScript anyway. It doesn’t exist. Pretending it does is limiting and over-complicated. Learn prototypical inheritance. It is far more powerful, and much simpler as well.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.