JavaScript three ways to create objects _js object-oriented

Source: Internet
Author: User
Tags eval http request
There are several ways to create objects in javascript:
(1) Using built-in objects
(2) using JSON notation
(3) Custom object construction

first, use the built-in objects

The built-in objects available to JavaScript can be grouped into two categories:
1,javascript Language native objects (language-level objects), such as String, object, function, etc.
2,javascript Runtime Host object (Environment host level object), such as window, document, body, and so on.

What we mean by using built-in objects is to instantiate a new object by constructing the native object of the JavaScript language. Such as:
Copy Code code as follows:

var str = new String ("instance initialization string");
var str1 = "Directly assigned string";
var func = new Function ("X", "Alert (x)");//Example initializes func
var o = new Object ();//Example Initializes an object

second, use the JSON symbol

(i) What is JSON?
JSON (JavaScript Object notation), named JavaScript, is a lightweight data interchange format that is easy to read and write, and easy to parse and generate. It is based on a subset of the JavaScript programming Language, Standard ECMA-262 3rd edition-december 1999. JSON is a completely language-independent text format and thus becomes the ideal format for data interchange.

JSON is a self of JavaScript, while ActionScript, C, C #, ColdFusion, E, Java, JavaScript, ML, Objectivecaml, Perl, PHP, Python, Rebol, The support of a range of languages, such as Ruby, LUA, makes JSON the preferred solution for AJAX development.

There are two ways to build JSON, one is a simple set of "key/value pairs", which is understood in different languages as objects, records, structures, dictionaries, hash tables, lists of keys, or associative arrays, and the other uses an ordered list of values that most languages interpret as arrays.

The common way to create is the first, which is the form of a "key/value pair" collection. In this form, an object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each name is separated by a ":" (a colon) and a "," (comma) between "key/value pairs".

JSON has the following characteristics: (1) Simple format of the data exchange, (2) easy to read and write habits, (3) easy to machine analysis and operation.
In JavaScript, JSON is understood as an object. With JSON as a string, the data can be easily parsed into JavaScript and read-pass data. Through JSON, the problem that JavaScript objects cannot be passed as parameter serialization is boarding to a certain extent.

1, simple JSON

{Name: "Andy Lau", Age: "Sex", "Man"}

Type of 2,json value

The value of JSON can be a simple data type, such as numbers, floating point, characters, and so on, and can also be arrays and objects. For example, a JSON with an array as the member key value:

{member:[{name: "Andy Lau"},{name: "Aaron Kwok"},{name: "Jacky Cheung"},{name: "Dawn"}]}

{
Book:[{name: "The Novel of the Kingdoms"},{name: "Journey to the"},{name: "The Water Margin"},{name: "Dream of Red Mansions"}],
Author:[{name: "Luo Guan Zhong"},{name: "en"},{name: "Schneider", {name: "Cao Xueqin"}]
}

3, using JSON in JavaScript

JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits, and JavaScript defaults to processing JSON as an object.

Pass an object to a variable, for example:
Copy Code code as follows:

var somebooks = {
Book:[{name: "The Novel of the Kingdoms"},{name: "Journey to the"},{name: "The Water Margin"},{name: "Dream of Red Mansions"}],
Author:[{name: "Luo Guan Zhong"},{name: "en"},{name: "Schneider", {name: "Cao Xueqin"}]
}

Each "key" of JSON is equivalent to an object's properties, such as accessing the first entry in the book, and in JavaScript, you can simply use "somebooks.book[0].name" to get the "Three Kingdoms" value.

Not only can we convert a JSON string into an object, but in turn "compile" an object into a JSON string to facilitate the transfer of objects in JavaScript. For example:
Copy Code code as follows:

var Animals = new Object ();
Animals.name = "Dog";
Animals.sex = "Male";
Animals.age = "2";

The animals object cannot be serialized for transmission, converting the animals object to a JSON string, which 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 expresses the object of JavaScript in a string form. Such as:
Copy Code code as follows:

var myObject = {nickname: ' My girlfried ', Name: ' Big Pig '};

JSON actually acts as a protocol for converting between JavaScript objects and strings. Since the "appearance" of JSON can be viewed as a string of villages, JSON can play a role in the transfer of JavaScript objects. For example, the object is strobject converted to a string, and then transformed to an object by the Eval method when the destination is reached:
Copy Code code as follows:

function Test (o)
{
Alert (O.name)
}
var strobject = ' {nickname: ' My Girlfriend ', Name: ' Big Pig '} ';
Test (eval ("+ Strobject +"));

three, custom object constructs

There are two ways to create advanced object constructs: Using the "this" keyword to construct, using a prototype prototype construct. Such as:
Copy Code code as follows:

Use the This keyword to define a constructed context property
function Girl ()
{
THIS.name = "Big pig";
This.age = 20;
this.standing;
This.bust;
This.waist;
This.hip;
}

Using 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);

The two definitions in the previous example have no difference in nature, and are the property information that defines the "Girl" object. The difference between "this" and "prototype" is primarily the order in which property is accessed. Such as:
Copy Code code as follows:

function Test ()
{
This.text = function ()
{
Alert ("defined by");
}
}
Test.prototype.test = function ()
{
Alert ("defined by prototype");
}
var _o = new Test ();
_o.test ()//output "defined by"

When accessing an object's properties or methods, it will follow the rules of the search prototype chain prototype chain. First, find the static properties, methods, and then find the accessible properties, methods, and finally the constructed prototype chain.

Another different point defined by "This" and "prototype" is that the property occupies a different space. Using the "This" keyword, the sample opens up the space required for each instance of the properties and methods that the constructor contains for each of the instances, using the "prototype" definition, because "prototype" is actually a reference to the parent, just a copy of the data, Therefore, both initialization and storage are more resource-saving 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.