[note] JavaScript advanced Programming-object-oriented programming

Source: Internet
Author: User
Tags shallow copy

ECMA-262 defines an object as: "A collection of unordered attributes whose properties can contain basic values, objects, or functions."

I. Understanding of the Object

The simplest way to create a custom object is to create an instance of an object and then add properties and methods to it.

1 Property Types

1) Data Properties

The Data property contains the location of a data value. Values can be read and written at this location. The data attribute has 4 attributes that describe its behavior.

    • [[Configurable]]: Indicates whether the property can be redefined by deleting the property from Delete, can modify the attribute's attributes, or can modify the property to an accessor property.
    • [[Enumerable]]: Indicates whether the property can be returned through a for-in loop.
    • [[writeable]]: Indicates whether the value of the property can be modified.
    • [[Value]]: Contains the data value for this property.

To modify the property's default attributes, you must use the ECMAScript 5 Object.defineproperty () method. This method takes three parameters: the object where the property resides, the name of the property, and a descriptor object. Where the properties of the descriptor (descriptor) object must be: Configurable, enumerable, writable, and value.

2) Accessor Properties

Accessor properties do not contain data values: they contain a pair of child getter and setter functions. When the accessor property is read, the Getter function is called, which is responsible for returning a valid value, and when writing the accessor property, the setter function is called and the new value is passed, which determines how the data is processed.

    • [[Configurable]]: Indicates whether the property can be redefined by deleting the property from Delete, can modify the attribute's attributes, or can modify the property to a data property.
    • [[Enumerable]]: Indicates whether the property can be returned through a for-in loop. The default value for this attribute is true for properties that are defined directly on the object.
    • [[Get]]: The function that is called when the property is read.
    • [[Set]]: The function that is called when the property is written.

Accessor properties cannot be defined directly and must be defined using Object.defineproperty ().

You do not have to specify both getter and setter at the same time. Specifying only getter means that the property is not writable, the attempt to write the property is ignored, and in strict mode, attempting to write a property that specifies only the Getter function throws an error. Similarly, properties that specify only setter functions are also unreadable, otherwise undefined are returned in non-strict mode, and errors are thrown in strict mode.

2 Defining multiple properties

Because of the high likelihood of defining multiple properties for an object, ECMAScript 5 also defines a object.defineproperties () method. This method allows you to define multiple properties at once by using a descriptor. This method accepts two object arguments: The first object is the object whose properties are to be added and modified, and the properties of the second object correspond to the property one by one to be added or modified in the first object.

3 properties of the Read attribute

Using the Object.getownpropertydescriptor () method of ECMAScript 5, you can get a descriptor for a given property. This method takes two parameters: the object where the property resides and the name of the property that reads its descriptor. The return value is an object, and if it is an accessor property, the object's properties are configurable, enumerable, get, and set, and if it is a data property, the object's properties are configuration, enumerable, Writable and value.

Second, create the object

1 Factory mode

function Createperson (name, age, Job) {    var o = {        name:name,        age:age,        job:job,         function() {            alert (this. Name);        }    };     return o;} var person = Createperson (' Greg ', ' Doctor ');

2 constructor mode

function Person (name, age, Job) {    this. Name = name;      this. Age = Age ;     this. Job = job;      This function () {        alert (this. name);}    ;} var person = new Person (' Greg ', ' Doctor ');

Unlike the factory model:

    • Object not explicitly created;
    • The properties and methods are assigned directly to the This object;
    • There is no return statement.

Calling a constructor in this way actually goes through the following 4 steps:

    1. Create a new object;
    2. Assigns the scope of the constructor to the new object;
    3. Executes the code in the constructor (adding attributes to the new object);
    4. Returns the new object.

1) Use constructors as functions

The only difference between constructors and other functions is that they are called in different ways.

// use as a constructor function var New Person (' Greg ', ' Doctor ');p erson.sayname (); // "Grey" // called as a normal function Person ("Grey", "Doctor"); Window.sayname (); // "Grey" // called in the scope of another object var New  "Kristen", "Nurse"); O.sayname ();

2) Problems with constructors

The main problem with constructors is that each method is recreated on each instance.

3 prototype mode

Each function has a prototype (prototype) attribute, which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type. The advantage of using a prototype object is that you can have all object instances share the properties and methods that it contains.

1) Understanding prototype objects

Whenever a new function is created, a prototype property is created for the function based on a specific set of rules, which points to the prototype object of the function. By default, all prototype objects automatically get a constructor (constructor) property, which is a pointer to the function where the prototype property is located.

After a custom constructor has been created, its prototype object will only get the constructor property by default, and the other methods are inherited from object. When the constructor is called to create a new instance, the inside of the instance contains a pointer (internal property) that points to the constructor's prototype object. ECMA-262 the 5th edition of this pointer is called [[Prototype]]. Although there is no standard way to access [[Prototype] in scripts, Firefox, Safari, and chrome support a property __proto__ on each object, and in other implementations, this property is completely invisible to the script.

Although [[Prototype]] is inaccessible in all implementations, the Isprototype () method can be used to determine whether the relationship exists between objects.

ECMAScript 5 Adds a new method called Object.getprototypeof (), which returns the value of [[Prototype]] in all supported implementations.

Although the values saved in the prototype can be accessed through an object instance, the values in the prototype cannot be overridden through an object instance. If we add a property to the example that has the same name as a property in the instance prototype, we create the property in the instance that will mask that property in the prototype.

Use the hasOwnProperty () method to detect whether a property exists in the sample or is present in the prototype. This method (do not forget that it is inherited from object) returns true only if the given property exists in the object example.

2) prototype and in operator

There are two ways to use the In operator: use separately and in the for-in loop. When used alone, the in operator returns True when the given property is accessible through the object, regardless of whether the attribute exists in the sample or in the prototype.

When you use the for-in loop, you return all the enumerable (enumerated) attributes that can be accessed through the object, including the attributes that exist in the instance, and also those that exist in the prototype. Instance properties that block non-enumerable properties in the prototype (that is, [[Enumerable]] that are marked as false) are also returned in the for-in loop, because all developer-defined properties are enumerable according to the rules.

To get all the enumerable instance properties on an object, you can use the Object.keys () method of ECMAScript 5. This method takes an object as a parameter and returns an array of strings containing all the enumerable properties.

If you want to get all the instance properties, whether it's enumerable or not, you can use Object.getownpropertynames ().

3) Simpler prototype syntax

function= {        "    Nicholas", "Software Engineer",     function() {        alert (this. Name);    }  } // Reset constructors, only for ECMAScript 5 compatible browsers Object.defineproperty (Person.prototype, "constructor", {    false,    value: person}

4) The dynamic nature of the prototype (important)

When the constructor is called, a [[Prototype]] Pointer to the original prototype is added to the instance, and modifying the prototype to another object is tantamount to cutting off the connection between the constructor and the original prototype.

function Person () {} var New  = {    Constructor:person,    "    Nicholas",    "Software" Engineer ",    function() {        alert (this. Name);    }}; Friend.sayname ();

In this example, we first create an instance of the person and then rewrite the prototype object. Then an error occurs when calling Friend.sayname () because a friend-directed prototype does not contain a property named by that name.

5) Problems with prototype objects

The biggest problem with prototype objects is caused by the nature of their sharing.

4 combining the constructor pattern with the prototype mode

The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties.

function Person (name, age, Job) {    this. Name = name;      this. Age = Age ;     this. Job = job;     this. Friends = ["Shelby", "Court"= {    Constructor:person,    function  () {        alert (this. Name);    }}

5 Dynamic Prototype mode

The dynamic prototype pattern encapsulates all the information in the constructor.

 function   person (name, age, job) { Span style= "COLOR: #008000" >//  this    . Name = name;     this . Age = age;     this . Job = job;  //  method   If  (typeof  this . Sayname! = " function ") {Person.prototype.sayName  = function< /span> () {alert ( this  .name"); }    }}

Iii. inheritance

1 prototype chain

The prototype chain is the main way to implement inheritance. The basic idea is to use a prototype to let one reference type inherit the properties and methods of another reference type.

function supertype () {    thistruefunction() {    return  This . prototype;} function subtype () {    thisfalse;} // inherited the supertype. New Subtype ();

1) Determine the relationship between the prototype and the instance

There are two ways to determine the relationship between a prototype and an instance. The first is to use the instanceof operator, as long as the operator is used to test the constructor in the instance and the prototype chain, and the result returns TRUE. The second way is to use the isPrototypeOf () method. Similarly, the isprototypeof () method also returns true as long as it is a prototype in the prototype chain that is a prototype of the instance derived from the prototype chain.

2) problems with the prototype chain

Although the prototype chain is large, it can be used to implement inheritance, but it also has some problems. Among them, the most important problem comes from prototypes that contain reference type values.

2 borrowing constructors

In the process of solving the problem of containing reference type values in the prototype, the developer began using a technique called borrowing constructors (constructor stealing) (sometimes called Pseudo-class objects or classic inheritance). The basic idea of this technique is quite simple, which is to call the superclass constructor inside the sub-type constructor.

function supertype () {    this. Colors = ["Red", "Blue", "green"];}  function subtype () {    Supertype.call (this);}

1) Passing parameters

With respect to the prototype chain, there is a great advantage to borrowing a constructor, that is, you can pass parameters to the superclass constructor in the subtype constructor.

2) The problem of borrowing a constructor function

If you simply borrow a constructor, you will not be able to avoid problems in the constructor pattern--methods are all defined in the constructor, so the reuse of the function is not possible.

3 Combination Inheritance

Combinatorial inheritance (combination inheritance), sometimes referred to as pseudo-classical inheritance, refers to the combination of the prototype chain and the technique of borrowing the constructor into a piece, thus exerting a succession pattern of both. The idea behind it is to use the prototype chain to implement the inheritance of the prototype properties and methods, and to implement the inheritance of the instance properties by borrowing the constructor function.

functionsupertype (name) { This. Name =name;  This. colors = ["Red", "Blue", "green"];} SuperType.prototype.sayName=function() {alert ( This);}functionsubtype (name, age) {//Inheritance PropertiesSupertype.call ( This, name);  This. Age =Age ;}//Inheritance MethodSubtype.prototype =Newsupertype (); SubType.prototype.constructor=subtype; SubType.prototype.sayAge=function() {alert ( This. age);};

4 prototype Inheritance

Prototypes allow you to create new objects based on existing objects without having to create custom types.

function Object (o) {    function  F () {}    = o;     return New F ();}

Inside the object () function, a temporary constructor is created, then the passed-in object is used as the prototype of the constructor, and finally an instance of the temporary type is returned. Essentially, an object () passed in to a shallow copy.

[Notes] "JavaScript advanced Programming"-object-oriented programming

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.