Code alerting an undefined message

Hi Gurus

I’m poking around with objects and the differences of creating a variable outside an object and inside an object. Here’s my code.

This is just before the closing body tag:


<script type="text/javascript">
// Creating an object
    
    // Old school way of creating variables - lotsa footprints
    
    var var1 = '';
    var var2 = '';
    var another = '';
    var more = function() {
        alert('Alert from the function');
    };
    
    
    // New way of accessing variable - one footprint
    
    var myObj = {
        var1 : 'something',
        var2 : 'something else',
        another : function() {
            alert('Hello there');
        }
    };
    
    alert(myObj.another());
</script>

When i reload the page, i get an alert box stating the 1st message “Hello there”

When i click on OK on the alert prompt. I get another prompt that says Undefined. I tried experimenting and found out that if i call the another() function within myObj without alerting it like so:

myObj.another();

Then i just get an alert prompt with “Hello there” only…the second undefined message doesn’t appear.

Why is this so. I want to really understand this. Thanking you in advance for reading this. :slight_smile:

Thank you so much :slight_smile:

Yes you can. And you don’t need to define it before that.
Just saying var MyObj = { … }; is enough :slight_smile:

No, and you shouldn’t. It breaks the javascript in older versions of IE :slight_smile:

Hi ScallioXTX,

i have a question on creating objects


// Let's say i initiate the object creation like so...
var MyObj = new Object;

// Now i want to add some properties for the object i created
var MyObj = {// Can i not use the var keyword and just start with MyObj = { }
var1 : 'something',
var2 : 'something else', // 1) Do i need to add the comma at the end of the last property?
};

When you fire alert(myObj.another()); what happens first is that myObj.another() is called, which shows the first alert – “Hello there”.
When that is done, the return value of myObj.another(); is alerted, but since the function didn’t return anything you get an alert that says “undefined”

Please try the following and run it again:


var myObj = {
        var1 : 'something',
        var2 : 'something else',
        another : function() {
            alert('Hello there');
            [B]return 'This is the return value of myObj.another()';[/B]
        }
    };

Hope that helps :slight_smile:

Thank you so much. That explanation was awesome. Totally understand what you explained.