JavaScript Beginner's object and JSON detail _ basics

Source: Internet
Author: User
JavaScript objects have little in common with traditional object-oriented objects, and in traditional object-oriented languages, creating an object must have a template for the object: A class, a class that defines the properties of an object, and how to manipulate those properties. By instantiating an object, and then using the collaboration between objects to complete a function, through the collection of functions to complete the project. And JavaScript is not the concept of the class, with the dynamic nature of JavaScript, we can create an empty object (instead of a class), through the dynamic add properties like objects to improve the function of the object.

JSON is the literal volume of objects in JavaScript and is the representation of objects, and by using JSON, you can reduce the intermediate variables, making the code clearer and more intuitive. Using JSON, you can dynamically build objects without having to instantiate them through classes, greatly improving the efficiency of coding.

JavaScript objects

A JavaScript object is actually a collection of attributes, where the set is equivalent to a mathematical set, which is deterministic, unordered, and heterosexual, that is, given a JavaScript object, we can clearly know whether a property is an attribute of the object, and the property in the object is unordered. , and are different (if there is one with the same name, then the declared overwrite is declared first).

In general, when we declare an object, the object is often just an empty set, does not contain any attributes, so that the object becomes a fully functional object by continually adding the property, rather than creating a class and then instantiating the class, so that our code is more flexible, We can arbitrarily delete the properties of the object.

If readers have the experience of Python or other similar dynamic languages, they can better understand the JavaScript object, which is itself a dictionary (dictionary), or a map in the Java language, or an associative array. That is, by using a key to correlate an object, which itself can be an object, we can know that a JavaScript object can represent any complex data structure.

object's Properties

Properties are made up of key-value pairs, which are the names of the properties and the values of the properties. The name of the property is a string, and the value can be any JavaScript object (all objects in JavaScript, including functions). For example, declare an object:
Copy Code code as follows:

Declaring an Object
var jack = new Object ();
Jack.name = "Jack";
Jack.age = 26;
Jack.birthday = new Date (1984, 4, 5);

Declaring another object
var address = new Object ();
Address.street = "Huang Quan Road";
Address.xno = "135";

Assign the Addr property to an object address
JACK.ADDR = address;

This kind of declarative object is very different from the traditional OO language, and it gives us great flexibility to customize the behavior of an object.

Object properties are read by using the dot operator (.) , such as the Addr property of the Jack object in the previous example, can be obtained in the following ways:
Copy Code code as follows:
var ja = jack.addr;
JA = jack[addr];

The latter is to avoid this situation by imagining that an object has a property that itself contains a point (.), which is legal in JavaScript, For example, the name is Foo.bar, and when using Jack.foo.bar, the interpreter mistakenly thinks that there is a bar field under Foo Property, so you can access it using Jack[foo.bar]. Generally speaking, when we develop a generic toolkit, we should not make any assumptions about the user's possible input, which is always guaranteed to be correct through the form of the property name.

Properties and variables

In the second chapter, we explain the concept of variables, and in this chapter, the reader may have noticed that the behavior of the two is very similar, in fact, the object's properties are the same as the variables we talked about previously.

When the JavaScript engine initializes, a global object is built, and in the client environment, the Global object is window. If you need to refer to this global object in another JavaScript environment, simply declare it in the top-level scope (the scope outside of all function declarations):

Copy Code code as follows:
var global = this;

The variables we declare in the top-level scope are saved as properties of the global object, and from this point of view the variables are actually attributes. For example, at the client, this code often appears:

Copy Code code as follows:
var v = "global";
var array = ["Hello", "World"];
function func (ID) {
var element = document.getElementById (ID);
Do some action on elemen
}

In fact the equivalent of:
Copy Code code as follows:

WINDOW.V = "global";
Window.array = ["Hello", "World"];
Window.func = function (ID) {
var element = document.getElementById (ID);
Do some action on elemen
}

Prototype Object
Prototype (prototype), a JavaScript-specific concept, through the use of prototypes, JavaScript can build their traditional oo language inheritance, thus reflecting the hierarchical relationship of objects. JavaScript itself is based on the prototype, each object has a prototype attribute, the prototype itself is an object, so it can also have its own prototype, thus forming a chain structure.
When accessing a property, the parser needs to traverse the chain structure from the bottom up until it encounters the property, return the value of the property, or encounter an object with a prototype null (the prototype attribute of the base object of JavaScript is null). Returns undefined if this object still does not have this property.
Let's look at a specific example:
Copy Code code as follows:

Declares an object base
function Base (name) {
THIS.name = name;
This.getname = function () {
return this.name;
}
}
Declaring an object child
function Child (ID) {
This.id = ID;
This.getid = function () {
return this.id;
}
}
Point the child's prototype to a new base object
Child.prototype = new Base ("base");
Instantiating a child object
var C1 = new Child ("Child");
C1 itself has a GetID method
Print (C1.getid ());
Because C1 inherits from the prototype chain to the GetName method, you can access the
Print (C1.getname ());

Come to the result:
Child
Base
Because there is a bottom when traversing the prototype chain, the first property value encountered is returned first, through which the mechanism of overloading can be completed.
This pointer
The easiest thing to confuse in JavaScript is to count this pointer, the this pointer is declared in a class in a traditional OO language, representing the object itself, and in JavaScript, this represents the current context, the caller's reference. Here we can look at a common example:
Copy Code code as follows:

Define a person, the name is Jack
var jack = {
Name: "Jack",
Age:26
}
Define another person, named Abruzzi
var Abruzzi = {
Name: "Abruzzi",
Age:26
}
To define a global function object
function Printname () {
return this.name;
}
Set Printname context for Jack, this is Jack.
Print (Printname.call (Jack));
Set the Printname context to Abruzzi, this is Abruzzi
Print (Printname.call (Abruzzi));

Run Result:
Jack
Abruzzi
It should be noted that this value is not determined by how the function is declared, but rather by how the function is invoked, which is quite different from the traditional object-oriented language, and call is a function on functions, described in detail in the fourth chapter.
Working with objects
Objects are the basis of JavaScript, and we use JavaScript to do programming by using objects, and this section uses some examples to learn how to work with JavaScript objects:
There are three different ways to declare objects:
By using the new operator, the object is constructed with a new object, and then the property is dynamically added to build a target from scratch.
Define the object's "class": the prototype, and then use the new operator to bulk build the object.
Use JSON, which is described in detail in the next section
In this section we describe in detail the second approach, such as:
Copy Code code 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 with the new operator, note that the two objects are separate entities
var jack = new Person (' Jack ', NUM, new address (' Qing Hai Road ', 123));
var Abruzzi = new Person (' Abruzzi ', 26);
View Results
Print (Jack.getname ());
Print (Jack.getage ());
Print (JACK.GETADDR ());
Print (Abruzzi.getname ());
Print (Abruzzi.getage ());
Print (ABRUZZI.GETADDR ());

The results of the operation are as follows:
Jack
26
Street:qing Hai Road, no:123
Abruzzi
26
Street:huang Quan Road, no:135

JSON and its use

JSON is all called the JavaScript Object notation (JavaScript objects notation), which is a literal representation of an object, which can be used in simple to complex ways. Like what:
Copy Code code as follows:

var obj = {
Name: "Abruzzi",
Age:26,
Birthday:new Date (1984, 4, 5),
Addr: {
Street: "Huang Quan Road",
Xno: "135"
}
}

This way, obviously more concise than the above example, there is no redundant intermediate variables, very clearly expressed the structure of an object such as obj. In fact, most experienced JavaScript programmers are more inclined to use this notation, including many JavaScript toolkits such as JQUERY,EXTJS, which use JSON a lot. JSON is actually a front-end and server-side data interchange format, front-end programs through Ajax to send JSON objects to the back end, server-side script to parse JSON, restore the server-side objects, and then do some processing, feedback to the front end is still a JSON object, using the same data format, can reduce the probability of error.

Moreover, the JSON-formatted data itself can be recursive, that is, to express arbitrarily complex data forms. JSON is written very simply by using a key-value pair enclosed in curly braces, where the key value is separated by a colon, and the value can be any JavaScript object, such as a simple object string,boolean,number,null, or a complex object such as Date,object, Other custom objects, and so on.

Another scenario for JSON is that when a function has multiple return values, in a traditional object-oriented language, we need to organize an object and then go back, and JavaScript doesn't have to bother at all, like:

Copy Code code 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 dynamically build a new anonymous object to return to:

Copy Code code as follows:
var pos = point (3, 4);
Pos.x = 3;
Pos.y = 4;

Returns an object using JSON, which can have any complex structure or even a function object.

In actual programming, we usually have to traverse a JavaScript object, and we know nothing about the object's content beforehand. How do you do it? JavaScript provides for ... In the form of grammatical sugars:

Copy Code code as follows:
For (var item in JSON) {
Item is key
Json[item] is a value
}

This pattern is useful, for example, in a real-world Web application where a page element needs to be set up with attributes that are not known beforehand, such as:

Copy Code code as follows:
var style = {
border: "1px solid #ccc",
Color: "Blue"
};

Then, we add these properties dynamically to a DOM element:

Copy Code code as follows:
For (var item in style) {
Using the selector for jquery
$ ("Div#element"). CSS (item, Style[item]);
}

Of course, jquery has a better way to do this, and here's just an example, and it should be noted that when we add attributes to $ ("div#element"), we are not clear about the structure of the style.

In addition, for example, we need to collect some user's custom settings, or by exposing a JSON object, the user fills in this JSON with what needs to be set, and then our program processes it.

Copy Code code as follows:
function Customize (options) {
this.settings = $.extend (default, Options);
}

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.