Methods for creating JavaScript objects _ js object-oriented

Source: Internet
Author: User
Objects in JavaScript can be created using built-in objects using JSON symbols to customize object structures. For more information, see. Objects in JavaScript can be created in the following ways:
(1) Use built-in objects
(2) Use the JSON symbol
(3) custom object construction

1. Use built-in objects

The built-in objects available in JavaScript can be divided into two types:
1. JavaScript native objects (Language-level objects), such as String, Object, and Function;
2. Host objects (Environment host-level objects) during JavaScript runtime, such as Windows, document, and body.

The built-in object is used to construct a new object through the construction method of the native object in JavaScript language. For example:

The Code is as follows:


Var str = new String ("instance initialization String ");
Var str1 = "String with direct value assignment ";
Var func = new Function ("x", "alert (x)"); // The example initializes func
Var o = new Object (); // The example initializes an Object.


Ii. Use the JSON symbol

(I) What is JSON?
JSON (JavaScript Object Notation) is a lightweight data exchange format, which is easy to read and write, and easy to parse and generate. It is based on a subset of JavaScript Programming Language, Standard ECMA-262 3rd Edition-December 1999. JSON is a language-independent text format, making it an ideal format for data exchange.

JSON as a JavaScript, at the same time, a series of languages such as ActionScript, C, C #, ColdFusion, E, Java, JavaScript, ML, ObjectiveCAML, Perl, PHP, Python, Rebol, Ruby, and Lua are supported, this makes JSON the preferred solution for Ajax development.

JSON can be constructed in two ways. One is a simple set of "key/value pairs, it is understood as an object, record, structure, Dictionary, hash table, key list, or associated array in different languages, and an ordered value list is also used, most languages regard it as an array.

The common creation method is the first, that is, the form of a "key/value pair" set. In this form, an object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon), and "," (comma) is used to separate "key/value" pairs.

JSON has the following features: (1) Simple formatted data exchange; (2) Easy reading and writing habits; (3) Easy Machine Analysis and operation.
In JavaScript, JSON is understood as an object. JSON in string form, data can be easily parsed into JavaScript exclusive and read and transmitted. JSON is used to solve the problem that JavaScript objects cannot be serialized as parameters.

1. Simple JSON

{Name: "Andy Lau", age: "25", sex: "male "}

2. JSON Value Type

JSON values can be simple data types, such as numbers, floating points, and characters, or arrays and objects. For example, JSON that uses an array as the member key value:

{Member: [{name: "Andy Lau" },{ name: "Guo Fucheng" },{ name: "Zhang Xueyou" },{ name: "Dawn"}]}

{
Book: [{name: "Romance of the Three Kingdoms" },{ name: "Journey to the West" },{ name: "Water Margin" },{ name: "Dream of Red Mansions"}],
Author: [{name: "Luo Guanzhong" },{ name: "Wu chengen" },{ name: "Shi Nai an", {name: "Cao Xueqin"}]
}

3. Use JSON in JavaScript

JSON is a JavaScript native format, which means that JSON data processing in JavaScript does not require any special APIs or toolkit. By default, JavaScript treats JSON as an object.

Pass an object to a variable, for example:

The Code is as follows:


Var somebooks = {
Book: [{name: "Romance of the Three Kingdoms" },{ name: "Journey to the West" },{ name: "Water Margin" },{ name: "Dream of Red Mansions"}],
Author: [{name: "Luo Guanzhong" },{ name: "Wu chengen" },{ name: "Shi Nai an", {name: "Cao Xueqin"}]
}


Each "key" in JSON is equivalent to the object property. For example, to access the first entry in the book, you can simply use "somebooks. book [0]. name to obtain the value of "Romance of the Three Kingdoms.

We can not only convert a JSON string into an object, but also "compile" an object into a JSON string to facilitate the transmission of objects in JavaScript. For example:

The Code is as follows:


Var Animals = new Object ();
Animals. name = "dog ";
Animals. sex = "Male ";
Animals. age = "2 ";


Animals objects cannot be serialized and transmitted. Animals objects are converted to JSON strings, that is, "{name:" dog ", sex:" Male ", age:" 2 "}". In this way, the JSON string is passed as a parameter of the HTTP request to achieve the purpose of serializing the Animals object.

(Ii) JSON represents JavaScript objects in the form of strings. For example:

The Code is as follows:


Var myObject = {nickname: "my girlfried", name: "big pig "};


JSON actually acts as a protocol for mutual conversion between JavaScript objects and strings. Because the "appearance" of JSON can be regarded as a string of but village, JSON can play a certain role in JavaScript Object transmission. For example, convert the object strObject into a string for transmission. After the object reaches the destination, use the eval method to restore it to an object:

The Code is as follows:


Function test (o)
{
Alert (o. name)
}
Var strObject = '{nickname: "my girlfriend", name: "big pig "}';
Test (eval ("(" + strObject + ")"));


3. Custom Object Construction

You can create an advanced object by using the "this" keyword and prototype. For example:

The Code is as follows:


// Use the this keyword to define the context attribute of the constructor.
Function Girl ()
{
This. name = "big pig ";
This. age = 20;
This. standing;
This. bust;
This. waist;
This. hip;
}

// Use prototype
Function Girl (){}
Girl. prototype. name = "big pig ";
Girl. prototype. age = 20;
Girl. prototype. standing;
Girl. prototype. bust;
Girl. prototype. waist;
Girl. prototype. hip;
Alert (new Girl (). name );


In the preceding example, the two definitions are essentially the same. They are the attribute information of the "Girl" object. The main difference between "this" and "prototype" lies in the order of attribute access. For example:

The Code is as follows:


Function Test ()
{
This. text = function ()
{
Alert ("defined by this ");
}
}
Test. prototype. test = function ()
{
Alert ("defined by prototype ");
}
Var _ o = new Test ();
_ O. test (); // output "defined by this"


When the attribute or method of the object to be accessed is. First, search for its own static attributes and methods, then find the accessible attributes and methods of the constructor context, and finally find the constructed prototype chain.

Another difference between "this" and "prototype" is that the space occupied by properties is different. Use the "this" keyword to open up all the attributes and space required by the constructor for each instance during the initialization of the example, and use "prototype" to define, because "prototype" is actually a reference pointing to a parent level, it is only a copy of data, so it saves resources in initialization and storage than "this.
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.