How to inherit from javascript object-oriented javascript _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to implement the inheritance of javascript and how to learn javascript object-oriented. If you are interested, refer to the examples in this article to introduce 6 methods for implementing the inheritance of javascript, the content is as follows:

1. [prototype chain inheritance]The essence of implementation is to override the prototype object and replace it with a new type of instance. In fact, not the constructor attribute of the SubType prototype is overwritten, but the prototype of the SubType is directed to another object-the prototype of SuperType, And the construtor attribute of this prototype object is directed to SuperType.

Function SuperType () {this. property = true;} SuperType. prototype. getSuperValue = function () {return this. property ;}; function SubType () {this. subproperty = false;} // inherits the SuperTypeSubType. prototype = new SuperType (); SubType. prototype. getSubValue = function () {return this. subproperty;} var instance = new SubType (); alert (instance. getSuperValue (); // true

[NOTE 1] define methods with caution. The code for adding methods to the prototype must be placed after the statement for replacing the prototype.

Function SuperType () {this. property = true;} SuperType. prototype. getSuperValue = function () {return this. property ;}; function SubType () {this. subproperty = false;} // inherits the SuperTypeSubType. prototype = new SuperType (); // added the SubType method. prototype. getSubValue = function () {return this. subproperty;} // rewrite the SubType method of the super type. prototype. getSuperValue = function () {return false;} var instance = new SubType (); alert (instance. getSuperValue (); // false

[NOTE 2] When the prototype chain is used for inheritance, you cannot use the object literal to create the prototype method. This will overwrite the prototype chain.

Function SuperType () {this. property = true;} SuperType. prototype. getSuperValue = function () {return this. property ;}; function SubType () {this. subproperty = false;} // inherits the SuperTypeSubType. prototype = new SuperType (); // adding a new method using the literal method will result in the previous line of code being invalid SubType. prototype = {getSubValue: function () {return this, subproperty ;}, someOtherMethod: function () {return false ;}; var instance = new SubType (); alert (instance. getSuperValue (); // error

[Disadvantage 1] when creating a child-type instance, parameters cannot be passed to a super-Type constructor.
[Disadvantage 2] prototype attributes containing reference type values will be shared by all instances

Function SuperType () {this. colors = ['red', 'blue', 'green'];} function SubType () {}// inherits SuperTypeSubType. prototype = new SuperType (); var instance1 = new SubType (); instance1.colors. push ('black'); alert (instance1.colors); // 'Red, blue, green, black' var instance2 = new SubType (); alert (instance2.colors ); // 'Red, blue, green, black'

2. [borrow constructor inheritance (also known as forged object or classic inheritance)] InThe subtype constructor calls the supertype constructor internally. Therefore, you can use the apply () and call () Methods to execute constructor functions on newly created objects in the future.

Function SuperType () {this. colors = ['red', 'blue', 'green'];} function SubType () {// inherits the SuperType. call (this);} var instance1 = new SubType (); instance1.colors. push ('black'); alert (instance1.colors); // 'Red, blue, green, black' var instance2 = new SubType (); alert (instance2.colors ); // 'Red, blue, green'

[Advantage] Passing Parameters

Function SuperType (name) {this. name = name;} function SubType () {// inherits the SUperType, And the SuperType parameter is also passed. call (this, "Nicolas"); // instance property this. age = 29;} var instance = new SubType (); alert (instance. name); // "Nicolas" alert (instance. age); // 29

[Note] to ensure that the SuperType constructor does not overwrite the sub-type attributes, you can add the attributes that should be defined in the sub-type after calling the super-Type constructor.

Function SuperType (name) {this. name = name; this. age = 30;} function SubType () {// instance attribute this. age = 29; // inherits the SUperType and the SuperType parameter is also passed. call (this, "Nicklas");} var instance = new SubType (); // The instance attribute is rewritten as the alert (instance. age); // 30

[Disadvantage 1] function reuse cannot be implemented.
[Disadvantage 2] The methods defined in the super-type prototype are invisible to sub-types, and only the constructor mode can be used for all results.
3. [combination inheritance (also known as pseudo-classic inheritance )]Combine the prototype chain with the borrow constructor technology to take full advantage of an inheritance mode. The idea behind it is to use the prototype chain to inherit the prototype attributes and methods, and use constructors to inherit the instance attributes. In this way, function reuse is realized by defining the method on the prototype, and each instance can have its own attributes, making it the most common inheritance mode in JavaScript.

Function SuperType (name) {this. name = name; this. colors = ['red', 'Blue ', 'green'];} SuperType. prototype. sayName = function () {alert (this. name) ;}; function SubType (name, age) {// inherits the SuperType attribute. call (this, name); this. age = age;} // Inheritance Method SubType. prototype = new SuperType (); SubType. prototype. constructor = SubType; SubType. prototype. sayAge = function () {alert (this. age);} var instance1 = new SubType ("Nicolas", 29); instance1.colors. push ("black"); alert (instance1.colors); // 'Red, blue, green, black' instance1. sayName (); // "Nicolas" instance1.sayAge (); // 29var instance2 = new SubType ("Greg", 27); alert (instance2.colors); // 'Red, blue, green'instance2. sayName (); // "Greg" instance2.sayAge (); // 27

[Disadvantage] two super-Type constructor calls in any situation: one is inside the sub-Type constructor when the sub-type is created. The child type will eventually contain all instance attributes of the super-type object, but you have to override these attributes when calling the child Type constructor.

Function SuperType (name) {this. name = name; this. colors = ["red", "blue", "green"];} SuperType. prototype. sayName = function () {alert (this. name) ;}; function SubType (name, age) {SuperType. call (this, name); // The second call of SuperType () this. age = age;} SubType. prototype = new SuperType (); // call SuperType () SubType for the first time. prototype. constructor = SubType; SubType. prototype. sayAge = function () {alert (this. age );};

4. [original type inheritance]The prototype allows you to create new objects based on existing objects without creating custom types. In essence, an object () performs a shortest copy on the objects that are passed in.
[Note] the original type inheritance requires that an object be used as the basis of another object. If such an object exists, it can be passed to the object () function, then, modify the object as needed.

function object(o){  function F(){};  F.prototype = o;  return new F();}var person = {  name: "Nicholas",  friends: ["Shelby","Court","Van"]};var anotherPerson = object(person);anotherPerson.name = "Greg";anotherPerson.friends.push("Rob");var yetAnotherPerson = object(person);yetAnotherPerson.name = "Linda";yetAnotherPerson.friends.push("Barbie");alert(person.friends);//"Shelby,Court,Van,Rob,Barbie"

[4.1] [Object. create () method]: ECMAScript5 adds the Object. create () method to normalize the original type inheritance. This method receives two parameters: an object used as the new object prototype and (optional) an object that defines additional attributes for the new object. When a parameter is passed in, the Object. create () and object () Methods behave the same

function object(o){ function F(){}; F.prototype = o; return new F();}var person = { name: "Nicholas", friends:["Shelby","Court","Van"]};var anotherPerson = Object.create(person);anotherPerson.name = "Greg";anotherPerson.friends.push("Rob");var yetAnotherPerson = object(person);yetAnotherPerson.name = "Linda";yetAnotherPerson.friends.push("Barbie");alert(person.friends);//"Shelby,Court,Van,Rob,Barbie"

[Note] The second parameter of the Object. create () method is in the same format as the second parameter of the Object. defineProperties () method: Each attribute is defined by its own descriptor. Any attribute specified in this way will overwrite the attributes of the same name on the prototype object.

var person = { name: "Nicholas", friends:["Shelby","Court","Van"]};var anotherPerson = Object.create(person,{ name: {  value: "Greg" }});alert(anotherPerson.name);//"Greg" 

[4.2] compatible with the Object. create () method in earlier browsers

if(typeof Object.create != "function"){ (function(){  var F = function(){};  Object.create = function(o){   if(arguments.length > 1){    throw Error('Second argument noe supported');   }   if(o === null){    throw Error("Cannot set a null [[Prototype]]");   }   if(typeof o != 'Object'){    throw TypeError("Arguments must be an object");   }   F.prototype = o;   return new F();  } })();} 

5. [parasitic inheritance]Create a function that is only used to encapsulate the inheritance process. The function enhances the object in some way internally and returns the object as if it did all the work.
[Disadvantage] function reuse cannot be implemented.

Function object (o) {function F () {}; F. prototype = o; return new F ();} function createAnother (original) {var clone = object (original); // create a new object clone by calling the function. sayHi = function () {// enhance the alert ("hi") ;}; return clone; // return this object} var person = {name: "Nicolas", friends: ["Shelby", "Court", "Van"]}; var anotherPerson = createAnother (person); anotherPerson. sayHi (); // "hi"

6. [parasitic combined inheritance]The constructor is used to inherit attributes and the methods are inherited through the mixed form of the prototype chain. The basic idea behind this idea is: you do not have to call a super-Type constructor to specify a sub-type prototype. You only need a copy of the super-type prototype. Essentially, it is to use parasitic inheritance to inherit the super-type prototype and then specify the result to the sub-type prototype. Parasitic combined inheritance is the ideal inheritance paradigm for reference types.

// The efficiency in this example is reflected in that it only calls the Super constructor once, and thus avoids creating unnecessary and redundant attributes on SubType. prototype. At the same time, the prototype chain remains unchanged. Function object (o) {function F () {}; F. prototype = o; return new F ();} function inheritPrototype (subType, superType) {var prototype = object (superType. prototype); // create the prototype object. constructor = subType; // enhancement object subType. prototype = prototype; // specify the object} function SuperType (name) {this. name = name; this. colors = ["red", "blue", "green"];} SuperType. prototype. sayName = function () {alert (this. name) ;}; function SubType (name, age) {SuperType. call (this, name); this. age = age;} inheritPrototype (SubType, SuperType); SubType. prototype. sayAge = function () {alert (this. age );}

The above is all about the content of this article. The method of javascript inheritance is appreciated!

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.