JavaScript OOP programming-three ways to implement inheritance

Source: Internet
Author: User

JavaScript OOP Programming-three forms of implementing inheritance [1]


(1) The way of simulating the class, we all know that JS is a prototype inheritance mechanism, there is no class and instance separation of this way

Let's say we have two of classes.


function Animal () {

THIS.name = "Animal";

This.eat = function () {

Consle.log ("eating");

}

}


function Cat () {

This.say = function () {

Console.log ("Miao miao!!");

}

}


If we want cat to have the animal name attribute and the Eat method, you only need to

Cat.prototype = new Animal ();

But this is not a good practice, think about, if there is a duck class, do you want to new a animal to inherit, so continue?

The right thing to do is to put the generic content into the prototype, all the heirs, simply point their prototype to a generic prototype to implement the inheritance.


As follows

Animal.prototype = {

Name: "Animal",

Eat:function () {

Console.log ("eating");

}

}


Cat.prototype = Animal.prototype;


ES5 provides us with a generic inheritance function that creates an object from a specified prototype

Object.create unfortunately not all browsers support, manually change


var inherit = Object.create | | function (proto) {

function F () {};

F.prototype = Proto;

return new F

}


The above example can be written as


Cat.prototype = Inherit (Animal.prototype);

——————————

In doing so, there will be cat.prototype = F case, we need to go to the right, we should write a package, specifically to implement the inheritance


var extend = function (child,parent) {

Child.prototype = Inherit (Parent.prototype);

Child.prototype.constructor = child;

}





JavaScript OOP Programming-three forms of implementing inheritance

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.