Part - 1 | Part - 2 | Part - 3 |
Object Oriented JavaScript
JavaScript does have an object data type – but these objects can behave differently from the objects we create in C# and VB code. In C# and VB we create new objects by telling the runtime which class we want to instantiate. A class is a template for object creation. A class defines the properties and methods an object will have, and these properties and methods are forever fixed. We can't manipulate an object by adding or removing properties and methods at runtime.
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;
JavaScript objects are entirely different from C# and VB objects because they are ultimately a collection of name and value pairs. We can access an object's values using the dot operator "." followed by the name of the value. A value isn't constrained to holding simple integer types as we have shown in the first example, but could hold an array, function, or even other object.If you are thinking a JavaScript object sounds like a Dictionary from the .NET framework class library, then you are heading in the right conceptual direction.
JavaScript Objects Are Dictionaries
A JavaScript object is similar to a Dictionary
Let's rewrite our first example using the [] operator.
p["x"] = 3;
p["y"] = 5;
message.innerHTML = p["x"] + "," + p.y;
The above piece of script produces the same result as our first script. It creates a new object, then adds x and y properties to the object, then writes out the values. Note that if we access a property that does not exist, we'll get back a value of "undefined". For instance, the line of code "alert(p.z);" would force a dialog box to appear with the string "undefined" insideCreating 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".
var p = new Object();
p["x"] = 3;
p.y = 5;
p["print"] = function()
{
message.innerHTML = p.x + "," + p.y;
}
p.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.Object Literals
The object literal syntax of JavaScript allows us to create an object and specify its properties using shorthand. The syntax uses a comma-separated list of name and value pairs, where the name and the value themselves are separated by a colon. Let's rewrite our code and create our object using this object initialization syntax.
var p =
{
x : 5,
y : 3,
print : function() { message.innerHTML = p.x + ',' + p.y; }
}
p.print();
In the above code it becomes clear where object initialization begins and ends. Also note that we can nest object literals, and that the property values inside the object literals do not need to be constants – we can use any legal JavaScript expression. The following code will contains a nested object (address), and assigns the current date to a new createdDate property.var person =
{
name: "Scott Allen", createdDate: new Date()
website: "OdeToCode.com",
address: { state: "MD", postalCode: "21044" },
};
alert(person.address.state);
alert(person.createdDate);
The object literal syntax is popular because of its explicit intent and compact size. If you look at the source code for many of today's popular JavaScript frameworks, you'll see they are using object literals inside. Frameworks, however, aren't the ones using object literals.Object Literals and JSON
JavaScript Object Notation (JSON) is a lightweight data-interchange format based on a subset of the object literal syntax. Technically, JSON is a stricter version of the object literal syntax. For example, string literals must be enclosed in double quotes – no single quotes are allowed.
JSON allows JavaScript to exchange data over the network (typically with the XmlHttpRequest object) and interoperate with other applications. Many web service providers offer JSON as a serialization format and as an alternative to XML. When our JavaScript contacts the web service, the web service will return its data in JSON. There is no need for our code to manipulate XML data with an XML API - instead our code can use JavaScript's eval statement to convert JSON into an object graph.
var jsonString = "({ x : 3, y: 5 })";
var p = eval(jsonString);
alert(p.x + ',' + p.y);
JSON is becoming hugely popular on the web. JSON is human readable and easily consumable in JavaScript. Also, exchanging data with JSON typically results in smaller payloads than using XML. ASP.NET AJAX includes a JavaScriptSerializer class to use JSON on the server-side in managed code. Part - 1 | Part - 2 | Part - 3 |
0 comments:
Post a Comment