JavaScript Custom Objects

Source: Internet
Author: User

Original: JavaScript Custom Object

In JS, in addition to the array, Date, number and other built-in objects, developers can create their own objects through the JS code.

Directory

1. Object properties: Describe the properties of an object

2. How to create objects: Object Direct amount, new constructor, Object.create (), etc. three ways

3. Serializing objects: Serializing and deserializing objects

4. Object-Oriented Programming: object-oriented simulations that describe custom objects; Include instance members, static members, and so on

5. Inheritance: Describes the inheritance characteristics of an object.

1. Object Properties

The ① structure resembles a ' dictionary ': An object's properties resemble a key/value pair; The name of the property is a string, and the value of the property is any type.

② prototype inheritance: JS objects inherit the properties of the prototype.

③ Dynamic Structure: The properties of the object can be dynamically added and deleted.

④ Reference type: The object in JS is a reference type. A is an object, b=a, and modifying B will also result in a modification.

2. How to create objects

JS in the creation of custom objects, mainly in three ways: the object direct amount, the new constructor and the Object.create () method. Each method of creation inherits the same prototype object :

① Object Direct Volume: Prototype is object.prototype.

②new constructor: Prototype is the prototype property of the constructor.

③object.create (): The prototype is the first parameter passed in, and if the first argument is null, Object.prototype is the prototype.

2.1 Object Direct Volume

Description: created directly from the property name/value.

syntax:var o = {name: ' Tom ', age:22};

Prototypes: Object.prototype

Application Scenario: applies to a specific scope.

Example:

var o = {    name: ' Tom '}console.log (O.constructor.prototype);//= = Object (): The prototype of the direct amount of objects is Objectconsole.log ( O.constructor.prototype = = = Object.prototype); True

2.2 New constructor

Description: The constructor is also a function, but in order to distinguish between the usual functions, the function name of the constructor is written in the form of a large camel peak (capitalized in the first letter).

syntax:var o = new ClassName ();

prototype: The prototype property of the constructor.

Example:

1. Create constructor function people (name) {    this.name;} var p = new People (' Tom '); Console.log (P.constructor.prototype); = = people{}: prototypeconsole.log (p.constructor.prototype = = = People.prototype) for the constructor of the prototype; + true//2. Multi-layered inheritance of custom objects: constructor returns the first call to the constructor function Student (age) {    this.age = age;} Student.prototype = new People (); Set the prototype for Student to people object var s = new Student (22); When the object is initialized, call people () before calling student () Console.log (s.constructor); = = function People: The constructor returned by Object S is Peopleconsole.log (S.constructor.prototype); = = people{}: Prototype object is Peopleconsole.log (S.constructor.prototype = = = People.prototype); = True

2.3 Object.create (prototype, PropertyDescriptor): ECMAScript 5 Specification

Description: creates and returns an object that specifies a prototype and a specified property.

Syntax: Object.create (prototype, PropertyDescriptor)

Parameters:

①prototype {prototype}: Creates a prototype of the object, which can be null. If NULL, the object's prototype is undefined.

②propertydescriptor {PropertyDescriptor} Optional: Property descriptor.

prototype: The Silent prototype is ①, and if the ① parameter is NULL, the prototype of the object is undefined.

Example:

1. Create a prototype null object var o = object.create (null, {    name: {        value: ' Tom '}    }); Console.log (o.constructor);//=& Gt Undefined//2. Create a prototype object for array var array = object.create (Array.prototype, {}); Console.log (Array.constructor); = = function Array constructor console.log (Array.constructor.prototype); = = []: Prototype objects are arrays//3. Create a prototype object for the custom class function people () {}var p = object.create (People.prototype, {}); Console.log (P.con Structor); = = function People constructor Console.log (P.constructor.prototype); = = people{}: Prototype Object people

3. Serialization

JS by calling the JSON method, you can serialize the object into a string or deserialize the string into an object.

3.1 Json.stringify (object): Serializes an object, converts the object into a string.

Parameters:

①object {Object}: Arbitrary object

return value:

{string} returns a converted string.

Example:

var o = {    x:1,    

3.2 Json.parse (JSONSTR): Converts a JSON string to an object.

Parameters:

①jsonstr {jsonstring}: a JSON string; attribute names in strings are quoted .

return value:

{Object} returns a converted Object

Example:

var str = ' {' x ': 1, ' Y ': 2} '; The property name of the string to be quoted box up var o = json.parse (str); Console.log (o.x); = 1: Output object property x value

4. Object-Oriented Programming

Simulates an object in a high-level language; Describes the attributes of instance members, static members, inheritance, and so on in advanced objects.

4.1 This keyword

Description: in the constructor, method member that creates the object, this points to the instance object itself.

Example:

var o = {    x:1,    y:2,    sayhello:function () {        console.log (this.x);//+ = 1: Reads the value of the instance object property x        console.log (x); = = Error: Read the variable x    }};o.sayhello ();

4.2 Instance Members

Syntax: instance object. Property name or Instance Object [property name]

There are several ways to add this:

① adds a member operation to this in the manner in which the object is created (constructors , object direct quantities, and so on).

② adds a member to the prototype object for the class name .

③ adds a member to an instance object (affects only the added instance, and no other instance has this member).

Example:

1. In the Create object mode, operate the This function people (name) {    this.name = name;} var p = new People (' Tom '); Console.log (p.name); = Tom: Read the value of the instance property name//2. Extending operations in the prototype object of a class People.prototype.sayHello = function () {    

4.3 Static members

Description: called directly through the class name

Syntax: class name. property name

How to add: Add members directly to the class name.

Example:

function people (name) {    this.name = name;} Add a static member to the class Hasname: Determine if the people instance contains the name attribute People.hasname = function (p) {    if (p.name && p.name.length > 0) {        return true;    }    return false;} var p = new People (' Tom '); People.hasname (P); = True

5. Inheritance

JS through the operation of the prototype, you can simulate the high-level language objects in the inheritance characteristics.

5.1 Single-Layer inheritance

Description: When you add a member to a class's prototype object (Classname.prototype), all instance objects of this class increase this member.

Example:

function people (name) {    this.name = name;} var P1 = new People (' Zhang San '), var p2 = new People (' John Doe ');//P1.sayname (); Error, instance does not have this member//Add members to the prototype object, all instances of the class will add this member People.prototype.sayName = function () {    alert (this.name);} P1.sayname (); POPs the value of the Name property P2.sayname (); The value of the Name property pops up

5.2 Multi-Layer inheritance

Description

If a class's prototype object (Classname.prototype) points to an object, this class inherits all instance members of the object, but does not inherit the static members of the object.

Example:

function people (name) {    this.name = name;    This.sayname = function () {        alert (this.name);    }} function Student (age) {    this.age = age;} Student.prototype = new People (); The prototype object for the set Student is the Prople instance object var st = new Student (n); st.name = ' Zhang San '; St.sayname (); = = Alert (' Zhang San '): Sayname member inherits from people class

  

================================== Series article ==========================================

This article: 3.8 JavaScript Custom Objects

Web Development Road Series articles

JavaScript Custom Objects

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.