This article mainly introduces how to use Object. getPrototypeOf to call the parent class method in the JavaScript subclass. For more information, see the prototype attribute of each function. Each object also has a prototype, which can be accessed through _ proto _ in Firefox/Safari/Chrome/Opera. Related interfaces are not provided in IE6/7/8.
The Code is as follows:
Function Person (){
This. method1 = function (){}
}
Person. prototype. method2 = function (){}
Function Man (){}
Man. prototype = new Person ();
Man. prototype. m1 = function (){}
Man. prototype. m2 = function (){}
Var m = new Man ();
For (var a in m. _ proto __){
Alert ();
}
Defines the parent class Person, subclass Man. New Man object, print all attributes.
ECMAScript V5 adds a static getPrototypeOf method for the Object (implemented by Firefox/Chrome) to obtain the Object prototype. It can be used to simulate Java's super.
The Code is as follows:
Function Person (){
This. method1 = function () {alert (1 )}
}
Person. prototype. method2 = function () {alert (2 );}
Function Man (){
This. m1 = function (){
Object. getPrototypeOf (this). method1 ();
}
}
Man. prototype = new Person (); // prototype inheritance
Man. prototype. m2 = function (){
Object. getPrototypeOf (this). method2 ();
}
Var man = new Man ();
Man. m1 ();
Man. m2 ();
The m1 method mounted on this in the subclass Man calls method1 mounted on this in the parent class Person, and the m2 method mounted on prototype calls method2 on the parent class prototype.
The above shows that the object prototype includes not only the properties on prototype, but also the properties on this in the constructor. Of course, due to the context in JavaScript, this in the parent class cannot be automatically converted in the subclass, and some skills are required.
This is the case in Java.
The Code is as follows:
Package bao1;
Class Person {
Private String name;
Person (String name ){
This. name = name;
}
Public void method1 (){
System. out. println (this. name );
}
}
Class Man extends Person {
Man (String name ){
Super (name );
}
Public void m1 (){
Super. method1 ();
}
}
Public class Test {
Public static void main (String [] args ){
Man man1 = new Man ("Jack ");
Man1.m1 ();
}
}