Summary of how objects are inherited in JavaScript (Super Classic)

Source: Internet
Author: User
Tags shallow copy
This article brings to you the content is about (Super Classic) JavaScript Object Inheritance method Summary, there is a certain reference value, the need for friends can refer to, I hope to help you.

First, the prototype chain inheritance

Focus: Use a prototype to have a reference type inherit the properties and methods of another reference type. Constructors, prototypes, relationships between instances: each constructor has a prototype object, and the prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object.

function supertype () {  this.property = true;} SuperType.prototype.getSuperValue = function () {  return this.property;}; Function subtype () {  this.subproperty = false;} Inherit from supertypesubtype.prototype = new Supertype (); SubType.prototype.getSubValue = function () {  return this.subproperty;}; var example = new subtype (); alert (Example.getsupervalue ());//true

Creating an object using a prototype has the problem of tampering with multiple instances of the operation of the reference type, which also has the following problem:

function supertype () {  this.colors = ["Red", "Blue", "green"];} Function subtype () {}//, even if not written, does not affect the result subtype.prototype = new supertype (); var example1 = new subtype (); Example1.colors.push ("Black"); alert (example1.colors); "Red,blue,green,black" var example2 = new subtype (); alert (example.colors); "Red,blue,green,black"

The Colors property of the two instance object example1 and example2 points to the same, changing one property that affects the other instance.

Disadvantages:
① The prototype chain inherits multiple instances of the reference type property pointing to the same, one instance modifies the prototype attribute, and the other instance's prototype property is also modified;
② cannot pass parameters;
③ inherit a single.

Second, borrowing constructor inheritance

Focus: Use. Call () and. Apply () to introduce the parent class constructor to the subclass function, using the constructor of the parent class to enhance the subclass instance, equivalent to copying the instance of the parent class to the subclass.

function Supertype (name) {  this.name = name;  This.colors = ["Red", "Blue", "green"];} Function subtype (name, age) {  //inherits from Supertype  Supertype.call (this, name);    This.age = age;} var example1 = new Subtype ("Mike"), Example1.colors.push ("Black"); alert (example1.colors);//"Red,blue,green,black "var example2 = new subtype (); alert (example2.colors);//" Red,blue,green "alert (example1.name); "Mike" alert (example1.age); 23

The key to borrowing the constructor inheritance is Supertype. Call (this, name), which invokes the Supertype constructor, so that each instance of subtype copies the attributes in the supertype.

Disadvantages:
① can inherit only the instance properties and methods of the parent class, and cannot inherit the prototype properties/methods;
② cannot implement the reuse of constructors, each subclass has a copy of the parent class instance function, which affects performance and the code is bloated.

Third, the combination of inheritance

Emphasis: Combining the advantages of both the prototype chain inheritance and the constructor inheritance , by calling the parent class construct, inheriting the properties of the parent class and preserving the arguments, and then implementing the function reuse by prototyping the parent class instance as a subclass.

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 attributes by borrowing the constructor , so that the function can be reused by defining the method on the prototype, and ensuring that each instance has its own properties.

function Supertype (name) {  this.name = name;  This.colors = ["Red", "Blue", "green"];} SuperType.prototype.sayName = function () {  alert (this.name);}; Function subtype (name, age) {  //Inherit attribute  Supertype.call (this, name);  This.age = age;} Inheritance method Subtype.prototype = new Supertype (); SubType.prototype.constructor = subtype; SubType.prototype.sayAge = function () {    alert (this.age);}; var example1 = new Subtype ("Mike"), Example1.colors.push ("Black"); alert (example1.colors); "Red,blue,green,black" Example1.sayname (); "Mike"; Example1.sayage (); 23var example2 = new Subtype ("Jack"); alert (example2.colors); "Red,blue,green" Example2.sayname (); "Jack"; Example2.sayage (); 22

Defects:
Instance properties and methods in the parent class exist in both instances of the subclass and in the prototype of the subclass, but only in memory footprint, so when you create an instance object using a subclass, there are two identical properties/methods in its prototype. ------- This method is the most common inheritance pattern in JavaScript .

Iv.. prototype-Type Inheritance

Emphasis: Wrapping an object with a function and then returning the call to that function, which becomes an instance or an object that can optionally add properties. Object.create () is the principle that directly assigns an object directly to the constructor's prototype.

function object (obj) {  function O () {}  o.prototype = obj;  return new O ();

Object () performs a shallow copy of the object passed in and points the prototype of O directly to the incoming object.

var person = {  name: ' Mike ',  friends: ["Jack", "Tom", "Joes"]};var Anotherperson = object (person); Anotherperson.name = "Greg"; AnotherPerson.friends.push ("Peter"); var Yetanotherperson = object (person); Yetanotherperson.name = "Linda"; YetAnotherPerson.friends.push ("BoBo"); alert (person.friends);   "Jack,tom,joes,peter,bobo"

ECMASCRIPT5 normalized the prototype inheritance by adding the Object.create () method, which receives two parameters: an object used as a prototype for a new object and an object that defines additional properties as a new object.

var person = {Name: "Evanchen", friends:["Shelby", "Court", "Van"];}; var Anotherperson = object.create (person); anotherperson.name = "Greg"; AnotherPerson.friends.push ("Rob"); var Yetanotherperson = object.create (person); yetanotherperson.name = "Linda"; YetAnotherPerson.friends.push ("Barbie"); Console.log (person.friends);//"Shelby", "Court", "Van", "Rob", "Barbie"

Disadvantages:
① The prototype chain inherits multiple instances of the reference type property pointing to the same (all instances inherit the properties on the prototype), there is the possibility of tampering;
② cannot pass parameters and cannot be reused. (The new instance properties are all added later).

V. Parasitic inheritance

Focus: Create a function that encapsulates the inheritance process, which internally enhances the object in some way, and finally returns the constructor. (like giving a shell to a prototype, and then return it)

function Createanother (original) {   varclone=object (original);//Call functions to create a new object  Clone.sayhi = function () {// Enhance this object in some way    alert ("HI");  };  return clone; Return Object}

The main purpose of the function is to add properties and methods to the constructor to enhance the function.

var person = {  name: ' Nicholas ',  friends: ["Shelby", "Court", "Van"]};var Anotherperson = Createanother (person); Anotherperson.sayhi (); "Hi"

Disadvantages:
① The prototype chain inherits multiple instances of the reference type attribute pointing to the same, there is the possibility of tampering;
② cannot pass parameters, is useless to prototypes, and cannot be reused.

Vi. Parasitic combined inheritance

Emphasis: Through the use of the constructor to pass parameters and parasitic patterns to implement inheritance properties, through the form of the prototype chain to inherit the method, in the function with apply or call to introduce another constructor, can be passed the parameter.

function Inheritprototype (subtype, supertype) {  var prototype = object.create (Supertype.prototype); Object.create Create object  prototype.constructor = subtype;                    Enhanced Object  Subtype.prototype = prototype;                      Specifies the object}//the parent class to initialize the instance property and the prototype attribute function supertype (name) {  this.name = name;  This.colors = ["Red", "Blue", "green"];} SuperType.prototype.sayName = function () {  alert (this.name);};/ /borrowing constructors to pass enhanced subclass instance properties (support for parameter and avoid tampering) function subtype (name, age) {  Supertype.call (this, name);  This.age = age;} The parent prototype is pointed to subclass Inheritprototype (subtype, supertype);//new Subclass prototype Attribute SubType.prototype.sayAge = function () {  alert ( This.age);} var example1 = new Subtype ("abc"), var example2 = new Subtype ("Def"), Example1.colors.push ("Pink"); ["Red", "Blue", "green", "Pink"]example1.colors.push ("Black"); ["Red", "Blue", "green", "black"]

The parasitic combination inherits the advantages of the preceding inheritance, almost avoids all the defects of the above inheritance method, and is the most efficient and the most widely used.

Disadvantages:
The process of implementation is relatively cumbersome.

Why learn these ways of inheritance, clearly can directly inherit why do you want to make such trouble? The main purpose is to learn their ideas, lay a better foundation for the future to read the framework source code, or their own packaging components and even framework of great benefits.

Time is a little hasty, not add ES6 extends.

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.