Object and JSON for getting started with JavaScript

Source: Internet
Author: User

JavaScript objects have almost no similarities with traditional object-oriented objects. In traditional object-oriented languages, creating an object must first have an object template: class, class defines the attributes of the object and the method to operate on these attributes. Construct an object through instantiation, use collaboration between objects to complete a function, and use a set of functions to complete the entire project. Javascript does not have the concept of classes. With the dynamic nature of JavaScript, we can create an empty object (rather than a class ), the function of the object is improved by dynamically adding attributes to the object.

JSON is the literal volume of objects in JavaScript and the representation of objects. By using JSON, you can reduce intermediate variables and make the code structure clearer and more intuitive. JSON can be used to dynamically construct objects without class instantiation, which greatly improves the coding efficiency.

Javascript Object

A JavaScript Object is actually a set of attributes. The set here is equivalent to a mathematical set, that is, it has certainty, no sequence, and no interaction. That is to say, given a JavaScript Object, we can clearly know whether a property is the property of this object. The attributes in the object are unordered and different (if there is a property with the same name, then the overwrite statement is declared first ).

In general, when we declare an object, the object is often only an empty set and does not contain any attributes. By constantly adding attributes, this object becomes a fully functional object, instead of creating a class and then instantiating the class mode, our code has higher flexibility and we can add or delete attributes of an object at will.

If you have experience in python or other similar dynamic languages, you can better understand JavaScript objects. JavaScript objects are actually dictionary objects or Map objects in Java, it is also called an associated array, that is, to associate an object through a key. This object itself can be an object. According to this definition, we can know that JavaScript objects can represent any complex data structure.

Object Attributes

An attribute is composed of key-value pairs, that is, the name of the attribute and the value of the attribute. The attribute name is a string, and the value can be any JavaScript Object (everything in JavaScript is an object, including a function ). For example, declare an object:
Copy codeThe Code is as follows:
// Declare an object
Var jack = new Object ();
Jack. name = "jack ";
Jack. age = 26;
Jack. birthday = new Date (1984, 4, 5 );

// Declare another object
Var address = new Object ();
Address. street = "Huang Quan Road ";
Address. xno = "135 ";

// Assign the addr attribute to the object address
Jack. addr = address;

This object declaration method is completely different from the traditional OO language. It gives us great flexibility to customize the behavior of an object.

The object attribute is read through the vertex operator (.). For example, the addr attribute of the jack object in the preceding example can be obtained through the following methods:
Copy codeThe Code is as follows: var ja = jack. addr;
Ja = jack [addr];
The latter is designed to avoid this situation. Assume that an object has an attribute that contains a vertex (.), this is legal in JavaScript, for example, the name is foo. bar, when jack. foo. bar, the interpreter will mistakenly assume that there is a bar field under the foo attribute, so jack [foo. bar. Generally, when developing a general toolkit, we should make no assumptions about possible user input. The [attribute name] format can always ensure correctness.

Attributes and variables

In the second chapter, we explain the concept of variables. In this chapter, readers may have noticed that these two behaviors are very similar. In fact, the attributes of an object are the same as the variables we mentioned earlier.

During initialization, the JavaScript engine constructs a global object. In the client environment, the Global object is window. If you need to reference this global object in other JavaScript environments, you only need to declare it in the top-level scope (that is, beyond the scope of all function declarations:

Copy codeThe Code is as follows: var global = this;
The variables declared in the top-level scope will be saved as attributes of the global object. From this point of view, the variables are actually attributes. For example, such code is often displayed on the client:

Copy codeThe Code is as follows: var v = "global ";
Var array = ["hello", "world"];
Function func (id ){
Var element = document. getElementById (id );
// Perform some operations on elemen
}
Actually equivalent:
Copy codeThe Code is as follows:
Window. v = "global ";
Window. array = ["hello", "world"];
Window. func = function (id ){
Var element = document. getElementById (id );
// Perform some operations on elemen
}

Prototype object
Prototype is a concept unique to JavaScript. By using prototype, JavaScript can establish inheritance in traditional OO languages to reflect the hierarchical relationship of objects. JavaScript itself is prototype-based, and each object has a prototype attribute. This prototype itself is also an object, so it can also have its own prototype, this forms a chain structure.
When accessing an attribute, the parser needs to traverse the chain structure from the bottom up until the attribute is met, then the corresponding value of the attribute is returned, or an Object whose prototype is null (the prototype attribute of the Base Object of JavaScript is null) is encountered. If this Object still does not have this attribute, undefined is returned.
Here is a specific example:
Copy codeThe Code is as follows:
// Declare an object base
Function Base (name ){
This. name = name;
This. getName = function (){
Return this. name;
}
}
// Declare an object child
Function Child (id ){
This. id = id;
This. getId = function (){
Return this. id;
}
}
// Point the child prototype to a new base object
Child. prototype = new Base ("base ");
// Instantiate a child object
Var c1 = new Child ("child ");
// C1 has the getId method.
Print (c1.getId ());
// Since c1 "inherits" from the prototype chain to the getName method, you can access
Print (c1.getName ());

Result:
Child
Base
Since there is a bottom-up link when traversing the prototype chain, the attribute values that are first encountered are first returned. This mechanism can be used to complete the reload mechanism.
This pointer
This pointer is probably the most confusing in JavaScript. In traditional OO languages, this pointer is declared in the class to indicate the object itself, while in JavaScript, this indicates the current context, that is, the caller's reference. Here we can look at a common example:
Copy codeThe Code is as follows:
// Define a person named jack
Var jack = {
Name: "jack ",
Age: 26
}
// Define another person named abruzzi
Var abruzzi = {
Name: "abruzzi ",
Age: 26
}
// Define a global function object
Function printName (){
Return this. name;
}
// Set the context of printName to jack. In this case, this is jack.
Print (printName. call (jack ));
// Set the context of printName to abruzzi. In this case, this is abruzzi.
Print (printName. call (abruzzi ));

Running result:
Jack
Abruzzi
It should be noted that the value of this is not determined by how the function is declared, but by how the function is called. this is completely different from the traditional object-oriented language, call is a Function on a Function. It is described in Chapter 4.
Objects used
Objects are the basis of JavaScript. We use JavaScript to complete programming by using objects. This section uses some examples to learn how to use JavaScript objects:
There are three methods to declare an object:
◆ Construct a new Object through the scope Object of the new operator, and then dynamically add attributes to construct an Object from scratch.
◆ Define the "class" of an object: prototype, and then use the new operator to create new objects in batches.
◆ JSON is used. This is detailed in the next section.
This section describes the second method in detail, for example:
Copy codeThe Code is as follows:
// Define a "class", Address
Function Address (street, xno ){
This. street = street | 'huang Quan Road ';
This. xno = xno | 135;
This. toString = function (){
Return "street:" + this. street + ", No:" + this. xno;
}
}
// Define another "class", Person
Function Person (name, age, addr ){
This. name = name | 'unknown ';
This. age = age;
This. addr = addr | new Address (null, null );
This. getName = function () {return this. name ;}
This. getAge = function () {return this. age ;}
This. getAddr = function () {return this. addr. toString ();}
}
// Create two objects using the new operator. Note that these two objects are mutually independent entities.
Var jack = new Person ('jack', 26, new Address ('qing Hai Road ', 123 ));
Var abruzzi = new Person ('abruzzi', 26 );
// View the result
Print (jack. getName ());
Print (jack. getAge ());
Print (jack. getAddr ());
Print (abruzzi. getName ());
Print (abruzzi. getAge ());
Print (abruzzi. getAddr ());

The running result is as follows:
Jack
26
Street: Qing Hai Road, No: 123
Abruzzi
26
Street: Huang Quan Road, No: 135

JSON and usage

JSON is called JavaScript Object Notation (JavaScript Object Notation), which means an Object is represented literally. This method can be used from simple to complex. For example:
Copy codeThe Code is as follows:
Var obj = {
Name: "abruzzi ",
Age: 26,
Birthday: new Date (1984, 4, 5 ),
Addr :{
Street: "Huang Quan Road ",
Xno: 135"
}
}

This method is much simpler than the preceding example. There is no redundant intermediate variable, which clearly expresses the structure of an object such as obj. In fact, most experienced JavaScript programmers prefer to use this notation, including many JavaScript toolkit such as jQuery and ExtJS, which use JSON in large quantities. JSON is actually a data exchange format between the front-end and the server. The front-end program sends a JSON object to the backend through Ajax. The server script parses the JSON object and restores it to a server object, then some processing is done, and the front-end is still a JSON object. using the same data format can reduce the error probability.

Furthermore, data in JSON format can be recursive, that is, it can express any complicated data format. JSON is easy to write, that is, key-value pairs enclosed in curly brackets. Key-value pairs are separated by colons, and values can be arbitrary JavaScript objects, such as simple objects such as String, Boolean, number, Null, or complex objects such as Date, Object, and other custom objects.

Another Application Scenario of JSON is: when a function has multiple return values, in the traditional object-oriented language, we need to organize an object and then return, javaScript does not need to be so troublesome, for example:

Copy codeThe Code is as follows: function point (left, top ){
This. left = left;
This. top = top;
// Handle the left and top
Return {x: this. left, y: this. top };
}
Directly and dynamically construct a new anonymous object and return it:

Copy codeThe Code is as follows: var pos = point (3, 4 );
// Pos. x = 3;
// Pos. y = 4;
Return objects in JSON format. This object can have any complicated structure or even include function objects.

In actual programming, we usually need to traverse a JavaScript Object, so we have no idea about the content of the object in advance. How can this problem be solved? JavaScript provides syntax sugar in the form of for... in:

Copy codeThe Code is as follows: for (var item in json ){
// Item is the key
// Json [item] is the value
}
This mode is very useful. For example, in actual WEB applications, you need to set some attributes for a page element. These attributes are unknown in advance, for example:

Copy codeThe Code is as follows: var style = {
Border: "1px solid # ccc ",
Color: "blue"
};
Then, we dynamically add these attributes to a DOM element:

Copy codeThe Code is as follows: for (var item in style ){
// Use the jQuery Selector
$ ("Div # element" ).css (item, style [item]);
}
Of course, jQuery has a better way to do this. Here is just an example. It should be noted that when we add attributes to $ ("div # element, the structure of the style is unclear.

For example, we need to collect some user-defined settings. We can also publish a JSON object. You can fill in the content to be set in this JSON object and then our program will process it.

Copy codeThe Code is as follows: function customize (options ){
This. settings = $. extend (default, options );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.