object creation and inheritance in JavaScript

Source: Internet
Author: User

JS is a prototype-based object-oriented language, compared with the traditional object-oriented such as java,c#, it has its own unique implementation in object creation and inheritance, this paper mainly describes the object creation and inheritance of JS in some of the practices.

1. Object creation

Mode one: Factory mode Create object

<script>    function Createperson (name,age,job)    {        var o=new Object ();        O.name=name;        O.age=age;        O.job=job;        O.sayname=function () {            alert (this.name);        };        return o;    }   This is the factory way to create the object    var a=createperson (' My ', ' student ');    A.sayname ();</script>

This approach is to pass the object property as a parameter into the function, then create a new object in the function and then return to the external use, is a typical input processing output mode, the advantage is simple and easy to understand and good to achieve the creation and isolation of objects, the disadvantage is that it does not conform to the typical OOP language to create object instances, And this creates objects that are of type object and cannot further determine which specific object type it belongs to.

Way two: Constructors Create objects

function Person (name,age,job) {        this.name=name;        This.age=age;        This.job=job;        This.sayname=function () {            alert (this.name);        }    }    var p1=new person (' my ', +, ' Stu ');//    This is the use of constructors to create objects    p1.sayname ();

This approach uses the function to emulate a class by invoking the constructor of the class to instantiate an object in new way, which conforms to the practice of the classic OOP creation instance object, and also to determine which specific type the instance belongs to, which is an instance of the person class.

, but the disadvantage of this approach is that the method of each instance is created once when the object is created, and the function is essentially an object, which wastes a lot of memory, and in fact, for many different instances their method is to reference a function relationship together.

Method Three: Create objects based on prototypes

<script>function person () {}person.prototype.name= ' my '; person.prototype.age=27; person.prototype.job= ' Stu '; Person.prototype.sayname=function () {    alert (this.name);} var p1=new person ();p 1.sayName ();</script>

This approach takes advantage of having a prototype for each function and multiple instances of it sharing the prototype's attributes and the properties and methods of that class on its prototype, which has the advantage of having multiple instances share a method definition, but it is also obvious that the constructor cannot be called by means of a parameter. Properties inside the constructor are hard-coded, and any instance's property modifications to its own reference type affect other instances

Mode four: constructor combined with prototype mode

Attributes placed    between constructors//instances do not affect each other function person    (name,age,job) {        this.name=name;        This.age=age;        this.job=job;    }   method is placed in the prototype    //Save Memory    person.prototype.sayname=function () {        alert (this.name);    }    Create objects using a combination    of Var p1=new person (' My ', ' Stu ');    P1.sayname ();

This approach combines the advantages of constructors and prototypes by placing definitions such as attributes such as 5 in the constructor, enabling isolation between different instances so that they do not interfere with each other, while also mounting the method definition onto the prototype, allowing multiple instances to share a method definition (method body), saving memory space, But this approach actually separates the two ways, and after the constructor is called, the prototype is manipulated, not in the way the classic OOP language creates objects.

Method Five: Dynamic prototyping mode

    function Person (name,age,job) {        this.name=name;        This.age=age;        This.job=job;        if (typeof this.sayname!= ' function ') {            this.sayname=function () {                alert (this.name);}}    }    var p1=new person (' My ', ' Stu ');    P1.sayname ();

In this way, the code of the method four operation prototype is put directly into the constructor, at the same time when the new instance of the type is judged, if there is a function instance, it is not created, otherwise create function, implement multiple instances to share a method body of the singleton mode, This mode is also widely used, and is a better way to create object instances.

On the basis of the good implementation of object creation, we discuss the inheritance in JS.

Mode one: Inheritance based on the prototype chain

function supertype () {        this.color=[' a ', ' B ', ' C '];    }    Function subtype () {    }    subtype.prototype=new supertype ();    var a1= new subtype ();    alert (a1.color);//a,b,c    A1.color.push (' d ');    var a2=new subtype ();    alert (a2.color);//a,b,c,d

The method is to point the prototype of the subclass to an instance of the parent class, which has the methods and properties of the parent class, but there are two drawbacks, one is that for a property of the parent class reference type, the other instance will be affected for any instance of its subclass on that property, and the other is that the subclass inherits the argument to the parent class. Inherited properties cannot be controlled and can only be completed by modification;

Method Two: Object impersonation inheritance

function person (name) {        this.name=name;        This.sayname=function () {            alert (this.name);        }    }    function Worker (name,age) {        person.call (this,name);        this.age=age;    }    var w1=new Worker (' my ', +);    alert (w1.name);    W1.sayname ();

This kind of inheritance method realizes to initialize the subclass by the pass parameter, achieves the isolation of the attribute methods between multiple instances, that is, does not affect each other, but similarly to the method inheritance because is calls the Call method executes the parent class constructor the code, equivalent each time must create a function, This is a waste of memory.

Method Three: Combining inheritance

function Supertype (name) {        this.name=name;    }    Supertype.prototype.sayname=function () {        alert (this.name);    }    Function subtype (name,age) {        supertype.call (this,name);        this.age=age;    }    Subtype.prototype=new supertype ();    Subtype.prototype.sayage=function () {        alert (this.age);    }    var s1=new subtype (' my ');    S1.sayage ();    S1.sayname ();

The method of this type is to take the inheritance of the property in the way of object impersonation, the inheritance of the method is based on the prototype chain, and the definition of the parent class itself also takes the above-mentioned attribute definition in the constructor, the method is defined in the prototype, so that the combination of the two different ways to complete the inheritance.

object creation and inheritance in JavaScript

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.