As we all know, C # uses traditional class inheritance, but in JS, it is not that simple, because it uses prototype inheritance, the implementation is a little more complicated. [Nonsense]
I was very impressed by one of the questions asked by the manager during the interview because I had not answered the question for a long time. How does JavaScript implement inheritance? Object-oriented has been used during the development process. Therefore, inheritance is also the most basic part. I have been in contact with JS for almost two years, and I have never passed this foundation, it seems that my theoretical work must be improved !!! I re-checked the information and finally got a deep understanding. So much nonsense, Coding Action...
[Body]
As we all know, C # uses traditional class inheritance, but in JS, it is not that simple, because it uses prototype inheritance, the implementation is a little more complicated.
The Code is as follows:
// Define the 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 ();
// Reference the created Me object to Me
Me. prototype. constructor = Me;
// Modify the Height attribute
Me. prototype. SetHeight = function (v ){
Me. prototype. Height = v;
}
// Adds a Stop action.
Me. prototype. Stop = function (){
Alert ("I'm Stop .");
}
Var m = new Me ();
// The result is People are 175 tall.
Alert ("People are" + m. Height + "cm tall .");
M. SetHeight (185 );
// The result is I'm 185 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 185 tall.
Alert ("You're" + y. Height + "cm tall .");
From the example above, we can see that the Me object inherits the People object, and can access the properties and actions of the People prototype, and have the actions and attributes of Me. Note that in the preceding example, a y = new Me () is instantiated, but when its Height attribute is displayed, It is not 175, instead of creating a new People implementation, the new Me () will reuse the prototype instance. Therefore, in the above example, all Me objects share the same Height attribute, which should be paid special attention to during inheritance and usage.