I am following a tutorial that is showing the factory pattern to create objects in javascript. The following code has me stumped as to why it works.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>6-2.htm</title>
</head>
<body>
<script type="text/javascript">
function createAddress(street, city, state, zip) {
var obj = new Object();
obj.street = street;
obj.city = city;
obj.state = state;
obj.zip = zip;
obj.showLabel = function() {
//alert(this.street + "\n" + this.city + ", " + this.state + " " + this.zip);
//var obj;
alert(obj.street + "\n" + obj.city + ", " + obj.state + " " + obj.zip);
};
return obj;
};
var JohnAddr = createAddress("12 A St.", "Johnson City", "TN", 37614);
var JoeAddr = createAddress("10061 Bristol Park", "Pensacola", "FL", 32503);
JohnAddr.showLabel();
JoeAddr.showLabel();
</script>
</body>
</html>
the first commented line seems proper to me (using the this
keyword in the showLabel function). i'm not sure how using obj in its place is working. obj would have to reference a global variable somewhere because within that function when its run there is no obj defined, right? since i make 2 objects, its not just luck in this case that both get displayed fine, the older values for obj's contents are stored and referenced properly. but how? if i uncomment the second comment then it breaks and i understand why, now im explicitly telling js that i'm talking about a local variable and there is none.