Home  >  Article  >  Web Front-end  >  JavaScript inheritance_javascript skills

JavaScript inheritance_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:01:261002browse

[Nonsense]
One of the questions I was asked by the manager during the interview impressed me deeply because I thought about it for a long time and couldn't answer it. The question is: How does JavaScript implement inheritance? Object-oriented has been used in the development process, so inheritance is also the most basic part. It has been almost two years since I started to work with JS. I have not even passed this basic level. It seems that my theoretical skills need to be improved. Increased intensity! ! ! I checked the information again and finally understood it deeply. So much nonsense, Coding Action...
[Text]
Everyone knows that traditional class inheritance is very simple in C#, but in JS, it is not so simple, because It uses prototype inheritance, which is relatively complicated to implement.

Copy code The code is as follows:

//Define People object
var People = function () { };
People.prototype = {
Height: 175,
Walk: function () {
alert("People are walking...");
}
}
//Define the Me object
var Me = function () { };
//Set the prototype attribute of Me to the People object
Me.prototype = new People();
//Point the reference of the created Me object back to Me
Me.prototype.constructor = Me;
//Modify the Height property
Me.prototype.SetHeight = function (v) {
Me. prototype.Height = v;
}
//New Stop action
Me.prototype.Stop = function () {
alert("I'm Stop.");
}
var m = new Me();
//The result is People are 175cm tall.
alert("People are " m.Height "cm tall.");
m.SetHeight(185 );
//The result is I'm 185cm tall.
alert("I'm " m.Height "cm tall.");
//The result is People are walking...
m.Walk();
//The result is I'm Stop.
m.Stop();
var y = new Me();
//The result is You're 185cm tall.
alert("You're " y.Height "cm tall.");

As can be seen from the above example, the Me object inherits the People object and can access the People prototype Me's attributes and actions can also have Me's own actions and attributes. It is important to note that in the above example, a y=new Me() is instantiated, but when its Height property is displayed, it is not the original 175, but the modified 185 by the m instance. Therefore, new Me() A new People implementation is not created, but an instance of its prototype is reused. Therefore, in the above example, all Me objects will share the same Height property. This should be paid special attention to when using inheritance.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn