Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
XML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
    var user = {
        name: "Doe, John",
        location: {
            address: "123 Main Street",
            city: "New York",
            state: "NY",
            zip: "10001",
            showAddress: function(){
                alert('The address of this user is: ' + this.location.address);
            }
        }
    };
</script>
</head>
<body>
<div>Why does the alert in the showAddress() function above say that "The address of this user is: undefined"?</div>
<div><button id="run" >Run</button></div>
<script>
    $(function(){
        $("#run").click(user.location.showAddress);
    });
</script>
</body>
</html>
Posted

Use this.address instead of this.location.address.


The showAddress function is called from location. So, this points to location - not to user...

 
Share this answer
 
v2
var user = {
name: &quot;Doe, John&quot;,
location: {
address: &quot;123 Main Street&quot;,
city: &quot;New York&quot;,
state: &quot;NY&quot;,
zip: &quot;10001&quot;,
showAddress: function(){
alert('The address of this user is: ' + <b>this.address</b>);
}
}
};
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900