JS object creation and how to inherit it

Source: Internet
Author: User

Look at the Red Book again, think a lot of knowledge to read more than a few times really can see more clearly. Today, I have revisited the object creation and inheritance, just a little bit down and consolidated.

JS is an object-oriented programming language, the ECMA-262 bar object is defined as: "A collection of unordered attributes, whose properties can contain basic values, objects, or functions." Each object is created based on a reference type, which can be either a native type or a custom one.

One, talk about how to create the object of several methods

1. var person = new Object ();

2. var person = {};

3. Factory mode

4. Constructor mode

5. Prototype mode

6. Combination of constructor mode and injustice pattern

7. Dynamic Prototyping Mode

8. etc....

Here the emphasis is on the construction pattern and prototype pattern, after all, after all, the model and inheritance methods are due to the advantages and disadvantages of these two.

4. Constructor mode

function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayname = function () {
Console.log (this.name);
};
}
var person1 = new Person (' Niko ', ' n ', ' FE ');

This way, you create an object that can be instantiated as a specific type in one. and instances can detect the type of an object by instanceof or constructor. The disadvantage is that the reuse of the method cannot be completed, that is, each method needs to be recreated on instantiation.

5. Prototype mode

We naturally want to create objects when we can share some properties and methods, the prototype pattern is very good ~ ~ ~ to show a face. To put it simply, each function we create has a prototype property, which is a pointer to an object that contains the prototype object of the object instance that was created. A prototype object, which is a property and method that contains all instances that are shared. By default, all prototype objects automatically get a constructor property that contains a pointer to the function where the prototype property is located. Around to get around the estimated dizzy, a figure to explain.

    

After creating the object through the prototype schema, it is possible to complete the sharing of properties and methods smoothly, but it is also a disadvantage if the value of the reference type is included, then an instantiated object will modify the value in the prototype so that the problem is more troublesome. So the combination pattern appears, and the constructor is used to create the attribute, and the prototype pattern is used to create the shared method.

7. The dynamic prototyping mode, which encapsulates all the information in a function, is a lot more concise, and it is also the advantage of combining constructors and prototype patterns to initialize the prototype within the function (initialized only at the first run).

      

function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
if (typeof this.sayname!= "function") {
Person.prototype.sayName = function () {
Console.log (this.name);
};
}

}
var person1 = new Person (' Niko ', ' n ', ' FE ');

Unlike the combination mode, the initialization prototype is inside the function, and if there are multiple shared functions, only one is OK ~ ~ Look at the simplicity of a small throw ~ ~ Object creation is written to this, then write a succession of La La ~

Second, the common way of inheriting

1. Prototype chain

2. Borrowing constructors

3. Combining inheritance

4. Combining parasitic inheritance

5. Prototype type, parasitic type.

Pick a few important points, it is important to master the principle of the prototype chain, as well as the structure of the inheritance method, the combination is to take these two advantages and disadvantages of optimization, combined parasitic is the optimization for the combination of inheritance. Prototype, parasitic is to a relative object to create another, not how to touch it.

1. Prototype chain

The main idea of a prototype chain is to have one reference type inherit another instance of the reference type. The prototype object will contain a pointer to another prototype, which also contains a pointer to another constructor. After the layers are progressive, a prototype chain is formed.

      

function Supertype () {
This.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
Function subtype () {
This.subproperty = false;
}
Subtype.prototype.getSubValue = function () {
return this.subproperty;
}
Subtype.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new Subtype ();

      

Ah, half a sudden to close the hall closed the hall of the =.= tears ran, the middle of the details do not explain, see this figure there is no big problem ~ The problem with the prototype chain is that when you share a reference type value, modifying an instance modifies the prototype.

2. Borrowing constructors

This method calls the constructor of the superclass in the subclass constructor.

  

function Supertype (name) {
THIS.name = name;
}
Function subtype () {
Supertype.call (This, ' Niko '); Call Supertype () in the scope of this
}
var instance = new Subtype ();

This is not like a prototype inheritance, it is equivalent to the scope of the subclass of the superclass of the properties of the completely copied copy. Because it is not a pointer to a reference, even if it is a property value of a reference type, each instance copies a copy of the property value, so there is no problem. And borrowing a constructor pattern can be used to pass parameters in a subclass.

3. Combination of inheritance is the advantages and disadvantages of both the prototype pattern and the borrowed constructor pattern. You can either share the method or let different instances have their own properties.

function Supertype (name) {
THIS.name = name;
this.colors = [' Red ', ' blue ', ' orange '];
}
SuperType.prototype.sayName = function () {
Console.log (this.name);
}
Function subtype (name,age) {
Inheritance Properties
Supertype.call (This,name); Second call to Supertype ()
This.age = age;
}
      
SubType.prototype.sayAge = function () {
Console.log (This.age);
}

Inheritance method

Subtype.prototype = new Suprtype (); Call Supertype () for the first time;
var instance = new Subtype (' Niko ', 34);

          

, the first time you tune the superclass, Subtype.prototype gets two properties: Name,colors. When you call the subtype constructor, the second time you call the superclass, create an instance property on the new object: Name,colors. These two instance properties mask the properties in the prototype.

This approach can be achieved by either sharing the method or having its own instance property, but calling the constructor of the two-time superclass.

4. Parasitic combined inheritance

In order to solve the combination of shortcomings, parasitic combination of this super Big Boss to play.

The general idea is to use the constructor to inherit the attribute, using the method of the prototype chain to the airport method. Instead of calling a superclass in a subclass, a copy of the superclass is obtained, unlike the composition.

      

function Inhertiprototype (subtype,supertype) {
var prototype = object (Supertype.prototype); Creating objects
Prototype.constructor = subtype;//Enhanced Object
Subtype.prototype = prototype;//The specified object
}

      

 

JS object creation and how to inherit it

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.