Yeasin Abedin
Yeasin Abedin

Reputation: 2453

JavaScript multiple alert promt

I have read about javascript function hoisitng. But in this case, i did not understood how anonymous functions are getting hoisted

var myObj = {
    name: 'MyName',
    dob: 10,
    office: 'MyOffice',
    myFun: function(){
        alert("Anonymous function");
    },
    showItem: function(){
        alert("Name : " + this.name + " office : " + this.office);
    }
};

alert(myObj.showItem());

If i run the code, two alert messages prompts. One shows the name, office and other undefined.

Upvotes: 1

Views: 87

Answers (2)

rosscj2533
rosscj2533

Reputation: 9323

The alert with the name and office comes from the showItem function itself, the alert(myObj.showItem()); shows undefined because it is alerting what is returned from showItem, which is nothing, therefore undefined.

Upvotes: 1

Shirkan
Shirkan

Reputation: 987

That's because two alerts are being called. The first is in showItem function in your var. The second is the wrapper alert of

alert(myObj.shwItem());

Try:

myObj.showItem();

In this case only the alert from within your defined var will be called.

Upvotes: 3

Related Questions