JavaScript inheritance and prototype inheritance usage detailed

Source: Internet
Author: User

Let's talk about the prototype prototype.

Each object has a prototype, the prototype is an object, modifying the object's prototype can affect all objects derived from this object, but modifying this object alone does not affect the prototype of the instance that has already been created. Because each object and prototype has a prototype, the object's prototype points to the object's parent prototype, and the parent prototype points to the parent prototype, a relationship that is connected through the prototype layer called the prototype chain, which is usually the default object prototype at the end of the chain.

JavaScript is an object-oriented language based on prototypes. In other words, each instance object has a prototype. Object inherits properties and methods from the prototype.
JavaScript is an object-oriented language based on prototypes. In other words, each instance object has a prototype. Object inherits properties and methods from the prototype.

1. Constructor function

With constructors, you can simply create objects. The This keyword within the constructor points to the instance object itself:

The code is as follows Copy Code

function people (name)
{
THIS.name = name;
}

To create an instance object using the new operator and constructor:

The code is as follows Copy Code

var people = new People (' xiaoming ');
Console.log (People.name); Xiao ming

However, if you create two instances, you cannot share properties and methods directly between these two instances:

The code is as follows Copy Code

var people1 = new People (' xiaoming ');
var people2 = new People (' Xiao Wang ');
People1.sex = ' Male ';
Console.log (People2.sex); Undefined

That is, once an object is instantiated, its property methods exist independently, and modifications to a property do not affect other instances.

2, Prototype

Then there is the prototype property, which is created automatically when the instance object is generated. It is an object in itself and has properties and methods that can be shared between instances. The properties and methods of the instance itself are included in the constructor. In other words, the properties and methods within the constructor, after being instantiated, become local properties and methods, whereas the properties and methods in the prototype (prototype) are simply references in the instance and can be shared by multiple instances.

Or just that constructor, now add the prototype attribute to it:

The code is as follows Copy Code

People.prototype.sex = ' female '; or write
People.prototype = {sex: ' female '};
Console.log (People1.sex); Male
Console.log (People2.sex); Female

The prototype property parameters of the people constructor directly affect the People1 and people2 two instances.

But why people1.sex output male? This is because in JavaScript, the prototype relationship exists in recursive form. An object's prototype is also an object, and the prototype itself may have a prototype. The highest level of the prototype is the global object.

This means that once the people1.sex is set to male, its corresponding value in the prototype cannot be exposed. If the people1.sex itself does not have a value, it is read from the constructor's prototype property, and so on, and so on, up until the object.

Note: Assign a value to an object using "null" to destroy the custom object and free the memory resource.


The prototype is read from the prototype chain and written to yourself.

A small example of inheritance

The code is as follows Copy Code

//inheritance
function person (name,sex)
{
this.name=name;
This.sex=sex;
}
Person.prototype.sayname=function ()
{
alert (this.name);
}
Person.prototype.saysex=function ()
{
alert (this.sex);
}
Function Worker (name,sex,job)
{
//Inheritance Person class
Person.call (this,name,sex)//This refers to an instance of the Worker class. As the following ' W ', the W is passed into the person constructor, and W is disguised as this
This.job=job in the person constructor.

//worker.prototype=person.prototype;//If such a negative stereotype is used, the Sayjob method of the subclass's parent class also has a Sayjob method, because it is a reference pass
// The subclass does not affect the parent class by changing to the following:
for (var i in Person.prototype)
{
Worker.prototype[i]=person.prototype[i];
}
Worker.prototype.sayjob=function ()
{
alert (this.job);
}
Var p=new person (' Lisi ', ' Male ');
//alert (p.sayjob);
var w=new Worker (' Zhangsan ', ' male ', ' soy sauce ');
W.sayname ();
W.saysex ();
W.sayjob ();

To express it more clearly, we create a pig class and inherit the animal class. How to create I will not say. The code that was created should be the same as it is now.

The code is as follows Copy Code

function Dog () {};
Dog.prototype = new Animal ("Henry");

function Pig () {};
Pig.prototype = new Animal ("Coco");

var dog = new Dog ();
Dog.jump ();
Dog.eat ();

var pig = new Pig ();

Pig.jump ();
Pig.eat ();

  

After running, because the reason that inherits the animal class, the result must be "xx is jumping ...", "XX is eatting ...", so what we want to achieve is to rewrite the method. We can implement a method rewrite in the following way.

  code is as follows copy code


function Dog () {};//Create Dog subclass
Dog.prototype = new Animal ("Henry");
Ways to Rewrite Dog
Dog.prototype.jump = function () {
Alert ("Hi, this is" + THIS.name + ", I ' m jumping ...")
};
Dog.prototype.eat = function () {
Alert ("Henry is eatting a bone now.");
};

function Pig () {};//Create Pig subclass
Pig.prototype = new Animal ("Coco");
Ways to rewrite Pig
Pig.prototype.jump = function () {
Alert ("I ' m sorry." + THIS.name + "can not jump.");
};
Pig.prototype.eat = function () {
Alert ("Hi, I ' m" + this.name + ", I ' m eatting something delicious.");
}

var dog = new Dog ();
Dog.jump ();
Dog.eat ();

var pig = new Pig ();

Pig.jump ();
Pig.eat ();

Run, is not the implementation of the method of rewriting it??

6. Then, if I instantiate a dog, I want to add properties and methods for this dog alone, how do I do that? Look underneath.

The code is as follows Copy Code

var dog = new Dog ();
Adding Properties and methods
Dog.type = "Doberman Pinscher";
Dog.shout = function () {
Alert ("I ' m a" + This.type + ".");
}
Dog.jump ();
Dog.eat ();
Calling a new method
Dog.shout ();

Well, this article is written here. I believe that beginners should have a certain understanding of class creation and inheritance. If you have any questions, you can leave a message.

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.