JS object-oriented in-depth understanding

Source: Internet
Author: User

JS object-oriented in-depth understanding

ECMAScript has two development modes: 1. Functional (procedural), 2. Object-oriented (OOP). An object-oriented language has a flag, which is the concept of a class, through which any number of objects with the same properties and methods can be created. However, ECMAScript does not have a class concept, so its objects are also different from those in class-based languages.

A Creating objects

Create an object, and then give the object new properties and methods.

var New // Create an Object // Create a Name property and assign a value // Create an Age property and assign a value function // Create a run () method and return a value return  This this. Age + ' running ... '// Output properties and method values
The above creates an object and creates properties and methods, and this in the Run () method represents the box object itself. This is the most basic way of JavaScript to create objects, but there is a disadvantage to create a number of similar objects, it will produce a lot of code.

To solve the problem of several similar object declarations, we can use a method called Factory mode, which is to solve the problem of instantiating objects that produce a lot of duplication.

functionCreateObject (name, age) {//centralized instantiation of functionsvarobj =NewObject (); Obj.name=Name;obj.age=Age;obj.run=function () {return  This. Name + This. Age + ' running ... ';};returnobj;}varBox1 = CreateObject (' Lee ', 100);//First InstancevarBox2 = CreateObject (' Jack ', 200);//a second instancealert (Box1.run ()); alert (Box2.run ());//remain independent

Factory mode solves the problem of repeated instantiation, but it has many problems, and the properties and methods of creating different objects are repeatedly established, consume memory, and function recognition problems and so on.

Two Methods of constructors

Constructor methods have some specifications:


1) The function name and instantiation construct name are the same and uppercase, (PS: not mandatory, but it helps to distinguish between constructors and
normal function);
2) Create an object from a constructor, you must use the new operator.

functionBox (name, age) {//constructor Mode This. Name =name; This. Age =Age ; This. Run =function () {return  This. Name + This. Age + ' running ... ';};}varBox1 =NewBox (' Lee ', 100);//new Box ()varBox2 =NewBox (' Jack ', 200alert (Box1.run ()); Alert (Box1instanceofBox);//clearly identified him from the box

Constructors can create the process of object execution:


1) When the constructor is used and the new constructor (), the new Object () is executed in the background;
2) The scope of the constructor to the new object (that is, the object created by new object), and this in the function body
Represents the object that is a new object ().
3) Execute the code within the constructor;
4) Returns the new object (returned directly from the background).

Note:

1) The only difference between a constructor and a normal function is that they are called in different ways. Simply, the constructor is also a function and must be called with the new operator, otherwise it is a normal function.

2) This is a reference that represents the current scope object. If this is the global scope, this represents the Window object, and if it is in the constructor body, it represents the object declared by the current constructor.

This method solves the problem of function recognition, but it does not solve the problem of consuming memory. At the same time, it brings a new problem, the global this is when the object is called the box itself, and as a normal function call, this also represents window. This is the problem with this scope.

Three. Prototypes

Each function we create has a prototype (prototype) attribute, which is an object whose purpose is to contain properties and methods that can be shared by all instances of a particular type. This is logically understood: prototype the prototype object of the object that was created by invoking the constructor. The benefits of using prototypes allow all object instances to share the properties and methods that it contains. That is, instead of defining the object information in the constructor, you can add the information directly to the prototype.

function // declaring a constructor // adding attributes to a prototype Box.prototype.age =function// Add method in prototype return This this. Age + ' running ... ';};

The way the constructor is declared and how the prototype pattern is declared is stored as follows:

Therefore, it solves the problem of consuming memory. Of course it can also solve problems such as this scope.

We often define attributes (some of which change the value of a property when instantiating an object) within a constructor, and add a common method to a prototype, which is a hybrid way of constructing the object (construction method + prototype mode):

var function (name) {   this. Name = name  };    function () {     returnthis. Name;   }   var New Person (' Zhangjiahao ');   // Zhangjiahao

The prototypes are detailed below:

1. Prototype objects

Each JavaScript object has a prototype object, which is implemented differently under different interpreters. For example, in Firefox, each object has a hidden __proto__ property, which is a reference to the "prototype object".

2. Prototype chain

Since the prototype object itself is also an object, according to the definition above, it also has its own prototype, and its own prototype object can have its own prototype, so that the formation of a chain, this is the prototype chain, the JAVASCRITP engine when accessing the object's properties, if not found in the object itself, Will go to the prototype chain to find, if found, the direct return value, if the entire chain is traversed and no property found, then return to undefined. The prototype chain is generally implemented as a list, so that it can be found in a certain order.

1) __proto__ and prototype
JS has a built-in property called __proto__ when creating an object (whether it is a normal object or a function object), and is used to point to the prototype object prototype of the function object that created it. Take the example above:

// true

Similarly, the Person.prototype object has the __proto__ property, which points to the prototype of the Function object (object) that created it.

// true

Continue, the Object.prototype object also has the __proto__ property, but it is more special, NULL

// NULL

We put this chain of __proto__ up until the object.prototype.__proto__ null is called the prototype chain. Such as:

2) constructor
The prototype object prototype has a predefined constructor property that references its function object. This is a circular reference

// true // true // true

3) to deepen our understanding , let us cite one more example:

functionTask (ID) { This. ID =ID; } Task.prototype.status= "STOPPED"; Task.prototype.execute=function(args) {return"Execute Task_" + This. id+ "[" + This. status+ "]:" +args; }      varTask1 =NewTask (1); varTask2 =NewTask (2); Task1.status= "ACTIVE"; Task2.status= "Starting"; Print (Task1.execute ("Task1")); Print (Task2.execute ("Task2"));
Results:
Execute Task_1[active]:task1execute Task_2[starting]:task2

The constructor automatically sets the prototype object Task.prototype for the Task1,task2 two objects, which are referenced by the prototype property of the task (in this most constructor), pointing to the arrow of the fancy.

Because the task itself is still a function, its "__proto__" property is Function.prototype, and the "__proto__" property of the built-in function prototype object is the Object.prototype object. The last Obejct.prototype "__proto__" value is null.

Summarize:

The __proto__ of the instance object points to the prototype of its constructor, and the constructor of the constructor prototype points to the corresponding constructor. The prototype of the constructor obtains the prototype of the constructor function.

Sometimes a reason constructor points to a problem that can be passed

Constructor: The name of the construction function;//constructor:task

Point again.

Four. Inheritance

Inheritance is a relatively central concept in object-oriented. Other Orthodox object-oriented languages implement inheritance in two ways: one is an interface implementation and one is inheritance. ECMAScript only supports inheritance, does not support interface implementations, and implements inheritance in a way that relies on the prototype chain.

In JavaScript, inherited functions are called supertype (parent class, base class, other language), inherited functions are called subtypes (subclass, derived class)

1.call+ traversal

The property uses the object impersonation (call), which essentially changes the pointer to the this, to inherit the base class, which is used to traverse the base class prototype.

functionA () { This. abc=12;} A.prototype.show=function() {alert ( This. abc);};//Inherit afunctionB () {//inherited attributes; this->new B ()A.call ( This);//Parameters can be passed parameter A.call (this,name,age)}//method of succession; b.prototype=a.prototype; for(varIinchA.prototype) {B.prototype[i]=a.prototype[i];}//add your own methodb.prototype.fn=function() {alert (' ABC ');};varobjb=NewB ();varObja=NewA (); Objb.show ();

Multiple inheritance can be implemented.

2. Parasitic combination inheritance

The main is Desk.prototype = new Box (); Desk inherits the box and forms the chain through the prototype. It is mainly implemented by temporary transfer function and parasitic function.

Temporary Transit functions: Create new objects based on existing objects without having to create custom types
Parasitic functions: The purpose is to encapsulate the process of creating objects

//Temporary transfer functionfunctionObj (o) {//o Indicates an object that will be passed intofunctionF () {}//The F-construct is a temporary new object used to store objects passed overF.prototype = O;//assign an O object instance to the prototype object of the F constructreturn NewF ();//and finally returns the object instance that gets passed over to the object.}//Parasitic FunctionsfunctionCreate (box, desk) {varf =obj (box.prototype); F.constructor= Desk;//adjusting the prototype construction pointersDesk.prototype =F;}functionBox (name) { This. Name =name; This. arr = [' apple ', ' pear ', ' orange '];} Box.prototype.run=function () {return  This. Name;};functionDesk (name, age) {Box.call ( This, name); This. Age =Age ;}//Inheritance through parasitic combination inheritanceCreate (Box, Desk);//This sentence is used to replace Desk.prototype = new Box ();varDesk =NewDesk (' Lee ', 100);d Esk.arr.push (' Peach 'alert (Desk.arr); alert (Desk.run ()) ;

Temporary transit functions and parasitic functions are mainly done by the workflow:

Temporary transit function: Returns an instance object function of the base class
Parasitic function: The constructor of the instance object function of the returned base class is pointed to the derived class, and the prototype of the derived class points to the instance object function of the base class (which is a function prototype), which implements inheritance.

--------------------------------------------------------------------------------------------------------------- ----------------------

Finish

Reproduced must be reproduced in the words, the original author and the original post address.

Read MORE:

http://www.108js.com/article/article1/10201.html?id=1092

JS object-oriented in-depth understanding

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.