<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>
Use this.address instead of this.location.address.
this.address
this.location.address
The showAddress function is called from location. So, this points to location - not to user...
showAddress
location
this
user
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)