JavaScript object-oriented Programming

Source: Internet
Author: User
Tags uppercase letter hasownproperty

Object-oriented languages have a sign that they all have the concept of a class, and that a class can create any number of objects with the same properties and METHODS.

Each object is created from a reference type that can be a previous primitive type, or it can be a developer-defined type.

1. Understanding the Object

① Property Type: There are two properties in ecmascript: data properties and accessor Properties.

(1) data properties: A data property contains the location of a data Value. In this position you can read and write values, and the data type has 4 characteristics that describe its behavior:

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. The default value is True

[[Enumerable]]: indicates whether the property can be returned through a for-in loop. The default value is True

[[writable]]: indicates whether the value of the property can be Modified. The default value is True

[[Value]]: contains the data value for this Property. When reading a property value, read from this position, and when writing the value of the property, save the new value in this position, default to undefined

To modify the properties default attribute, use the ECMAScript5 object.defineproperty () method. This method receives 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. Set one or more of these values to modify the corresponding attribute Values.

(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. Accessor properties have the following 4 attributes:

[[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. The default value is True

[[Enumerable]]: indicates whether the property can be returned through a for-in loop. The default value is True

[[Get]]: the function that is called when the property is read, the default value is undefined

[[Set]]: the function that is called when the property is written, the default value is undefined

Accessor properties cannot be defined directly, you must use Object.defineproperty () to define

② Defining multiple properties

Because of the high likelihood of defining multiple properties for an object, ECMAScript5 defines a object.defineproperties () method. This method allows you to define multiple properties at once by using a Descriptor. This method receives 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.

③ Properties of Read attributes

The ECMAScript5 object.getownpropertydescriptor () method allows you to obtain a descriptor for a given Property. This method receives two parameters: the object where the property resides and the name of the property whose descriptor you want to READ. The return value is an object, which can be an accessor property or a data Property.

In javascript, you can use the Object.getownpropertydescriptor () method for any object-including dom and BOM Objects.

2. Create objects

Although the object constructor or object literal can be used to create a single object, there are obvious drawbacks to these approaches: creating many objects using the same interface creates a lot of duplicate code. To solve this problem, people began to use a variant of the factory model.

The ① factory model is a well-known design pattern in the field of software engineering that abstracts the process of creating concrete objects. Considering the inability to create a class in ecmascript, the developer invented a function that encapsulates the details of creating an object with a specific interface.

This function can accept parameters to construct a person object that contains all the necessary Information. This function can be called several times, and each time it returns an object that contains a method of three Attributes. Factory mode solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (that is, How to know the type of an object). With the development of javascript, a new paradigm has emerged.

② Constructor Mode:

The difference from the factory mode: (1) the object created without a display (2) assigns properties and methods directly to the This object (3) without a return statement.

As a rule, constructors should always start with an uppercase letter, while non-constructors should start with a lowercase letter.

In this example, Person1 and Person2 each hold a different instance of Person. Both objects have a constructor (constructor) property that points to person:

The constructor property of an object is originally used to identify the object Type.

Creating a custom constructor means that its instance can be identified in the future as a specific type, which is where the constructor pattern trumps the factory Pattern. In this example, Person1 and Person2 are both instances of object because all objects inherit from Object.

(1) use constructors as functions: the only difference between constructors and other functions is that they are called in different ways. however, constructors are functions after all, and there is no special syntax for defining constructors. Any function, as long as it is called by the new operator, can be used as a constructor, and any function, if not called by the new operator, is no different from the normal Function.

(2) the problem with constructors: each method is recreated on each instance. You can solve this problem by moving the function definition outside the Constructor.

The new problem is that a function defined in the global scope can actually be called only by an Object. Even more unacceptable is that if an object needs to define many methods, it is necessary to define many global functions. Prototype mode can be Resolved.

③ prototype Mode:

Each function we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type.

Prototype is the prototype object of the object instance that was created by invoking the Constructor. The advantage of using a prototype object is that you can have all object instances share the properties and methods that it contains.

Instead of defining the information for an object instance in the constructor, you can add that information directly to the prototype Object.

(1) Understanding Prototype Objects:

Multiple object instances share the rationale for the properties and methods saved by the prototype: when the code reads a property of an object, the search is performed once, and the target is a property with the given Name. The search begins first from the object instance Itself. If a property with the given name is found in the instance, the value of the property is Returned. If it is not found, continue searching for the prototype object pointed to by the pointer, looking for the property with the given name in the prototype Object. If found, returns the value of the Property.

The prototype initially contains only the constructor property, which is also shared, so it can be accessed through an object instance

When you add a property to an object instance, This property masks the property that is saved in the prototype object with the same name. Adding this property prevents us from accessing that property in the prototype, but does not modify that Property. Even if this property is set to null, this property is only set in the instance, not its connection to the prototype, but the delete operator can be used to remove the instance properties, allowing us to revisit the properties in the Prototype.

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

True is returned only if Person1 overrides the name property, because this is the only time that name is an instance property, not a prototype Property.

(2) prototypes and in operators

There are two ways to use the in operator: use separately and in the For-in loop.

Used alone: The In operator returns True when the given property is accessible through the object, whether the attribute exists in an instance or in a prototype

Using both the hasOwnProperty () method and the in operator, you can determine whether the attribute is present in the object or in the prototype

Because the in operator returns True,hasownproperty () only if the property is accessible through the object, returns true only if the property exists in the instance, so long as the in operator returns true, and hasOwnProperty () returns false, You can determine that the property is a property in the prototype

The Name property first exists in the prototype, so Hasprototypeproperty () returns True. When the Name property is overridden in an instance, the property is present in the instance, so Hasprototypeproperty () returns false.

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

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

If it is called through the person instance, the array returned by Object.keys () contains only the "name" and "age" two instance Properties.

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

Note The constructor attribute is included in the Results. Both the Object.keys () method and the Object.getownpropertynames () method can be used instead of the for-in loop.

(3) Simpler prototype syntax

Overriding an entire prototype object with an object literal that contains all the properties and methods

We set the Person.prototype equal to a new object created as an object literal, with the same end result, with one exception: the construction property no longer points to Person. The constructor property becomes the constructor property of the new object (pointing to the object Constructor) and no longer points to the person Function.

(4) The dynamic nature of the Prototype.

(5) prototype of native Object:

The importance of prototype patterns is not only in the creation of custom types, but even in all native reference types, which are created using this Pattern. All native reference types (Object, Array, string, and so On) define methods on the prototype of their constructors.

④ combination using constructor mode and prototype mode

The most common way to create custom types is by combining the constructor pattern with the prototype Pattern. The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared Properties. As a result, each instance will have its own copy of the instance properties, but at the same time it shares a reference to the method, saving the memory to a minimum. This blending mode also supports passing parameters to Constructors.

This is a default pattern for defining reference types

⑤ Dynamic Prototyping Mode

This code will only be executed when the constructor is first called, and after that the prototype has been initialized and no further modifications are Required. The modifications made to the prototype here can be immediately reflected in all Instances.

You cannot use object literals to rewrite prototypes when using dynamic prototype Mode. If you rewrite the prototype with the instance already created, the connection between the existing instance and the new prototype is Severed.

⑥ Parasitic structural function pattern

The parasitic (parasitic) constructor pattern can be used in cases where none of the preceding modes are Applicable. The basic idea of this model is to create a function that encapsulates the code that creates the object, and then returns the newly created object, but on the surface, the function looks like a typical Constructor.

3, inheritance: ECMAScript only support the implementation of inheritance, and its implementation of inheritance is mainly based on the prototype chain to Achieve.

① prototype Chain: ECMAScript describes the concept of the prototype chain, and the prototype chain as 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.

Subtypes sometimes need to overwrite a method in a superclass, or you need to add a method that does not exist in the super Type. The code that adds a method to the prototype must be placed after the statement that replaced the Prototype.

Problem with the prototype Chain: (1) a prototype that contains a reference type Value. When you implement inheritance through a prototype, the prototype actually turns back into an instance of another Type. (2) When you create an instance of a subtype, you cannot pass parameters to the constructor of the superclass Type. In practice, the prototype chain is seldom used Alone.

② borrowing constructors: in the process of solving the problem of containing reference type values in the prototype, the developer begins to use a technique called borrowing Constructors. The basic idea is that the Sub-type constructor calls the Super-type constructor internally.

③ combination Inheritance: also known as pseudo-classical inheritance, refers to the prototype chain and borrowed the technology of the constructor into a piece, so as to play both the length of an inheritance Model. The idea is to use the prototype chain to implement the inheritance of the prototype properties and methods, and to implement the inheritance of instance properties by borrowing Constructors. This enables the reuse of functions by defining methods on the prototype, and ensures that each instance has its own properties.

④-prototype inheritance:

Inside the object () function, create a temporary constructor, then use the incoming object as a prototype of the constructor, and finally return a new instance of the temporary Type.

ECMAScript5 normalized the stereotype inheritance by adding the Object.create () method. This method receives two parameters: an object that is used as a prototype for the new object and (optionally) an object that defines additional properties for the new Object. In the case of passing in a parameter, the object.create () behaves the same as the Object () method.

⑤ Parasitic Inheritance

Parasitic inheritance is closely related to prototype Inheritance. The idea of parasitic inheritance is similar to the parasitic constructor and factory pattern, which is to create a function that encapsulates the inheritance process, which in some way enhances the object, and finally returns the object as if it did all the Work.

⑥ Parasitic combined inheritance: combined inheritance in any case, the two-time superclass constructor is called, one time when creating a prototype of a subtype, and the other is inside the constructor of the Subtype.

The subtype eventually contains all the instance properties of the superclass Object.

Parasitic combined inheritance, that is, by borrowing the constructor to inherit the property, through the combination of the prototype chain to inherit the Method. The idea is that you don't have to call a Super-type constructor to specify a prototype for a subtype, all we need is a copy of the Super-type Prototype.

JavaScript 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.