Javascript Lesson 1 - Object Funadamentals
by ironicmuffin
HTML
<html>
<head>
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<h1>Javascript Lesson 1 - Object Funadamentals</h1><br />
<p>Example 1: <span id="message"></span></p><br />
<p>Example 2: <span id="message_2"></span></p><br />
<p>Example 3: <span id="message_3"></span></p><br />
<p>Example 4: <span id="message_4"></span></p><br />
<p>Example 5: <span id="message_5"></span></p><br />
</body>
</html>
CSS
h1 {
font-weight: bold;
font-size: 18px;
margin: 5px;
}
p {
margin: 5px;
}
JavaScript
/* Objects
In JavaScript there are no classes, so we have no template for object creation. Then how do properties and methods become part of an object? One approach is to dynamically create new properties and methods on an object after construction. To create a new property, all we need to do is assign a new value for a property. The following code creates a new object, then adds an x and y property to the object. Finally, the script writes the values of the two new properties into an area in the HTML document.
*/
var p = new Object();
p.x = 3;
p.y = 5;
message.innerHTML = p.x + "," + p.y;
/* Objects are essentially dictionaries
A JavaScript object is similar to a Dictionary<string, object> in the sense we can associate any arbitrary piece of data with any arbitrary string. In fact, there is an alternate syntax for accessing the values inside an object which makes the object look exactly like a dictionary. Instead of using the . operator to access a value, we can use the [] operator. The [] operator is a common sight when we work with collections like arrays, dictionaries, and hashtables.
*/
p = new Object();
p["x"] = 3;
p["y"] = 5;
message_2.innerHTML = p["x"] + "," + p.y;
/* Object Methods
We can also add functions into the collection of values inside an object. Functions associated with an object become methods of the object. The following code sample shows how to create and use a method with the name of "print".
Notice we alternate use of the . operator and the [] operator. We can use these two operators interchangeably, for the most part, to create and access an object's properties and methods. Sometimes these operators lead to confusion, because it's not clear if a particular piece of code is trying to create new properties on an object, or if it's trying to set existing properties to new values. Fortunately, there is a third syntax available that makes our intent explicitly clear.
*/
p = new Object();
p["x"] = 3;
p.y = 5;
p["print"] = function() {
...