Home >Web Front-end >JS Tutorial >How does a JS subclass use Object.getPrototypeOf to call the parent class?
This time I will show you how to use Object.getPrototypeOf to call the parent class in a JS subclass. The following is a practical case. Let’s follow the editor’s footsteps and take a look.
Each function has a prototype attribute, called the prototype. Each object also has a prototype, Firefox/Safari/Chrome/Opera It can be accessed through __proto__, and there is no relevant interface provided in IE6/7/8.
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(a); }
defines the parent class Person and the subclass Man. new a Man object and print out all properties.
ECMAScript
V5 adds a static getPrototypeOf method to Object (Firefox/Chrome has implemented it
), used to obtain the prototype of the object. It can be used to imitate Java's super.
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();//原型继承 Man.prototype.m2 = function(){ Object.getPrototypeOf(this).method2(); } var man = new Man(); man.m1(); man.m2();
The m1 method hanging on this in the subclass Man calls the method1 hanging on this in the parent class Person, and the m2 method hanging on the prototype calls method2 on the parent class prototype.
It can be seen from the above that the object prototype not only includes the attributes on its constructor prototype, but also includes the attributes on this in the constructor. Of course, due to context reasons in JavaScript, this in the parent class cannot be automatically converted in the subclass, and some skills are required to complete it.
This is how it works in Java
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(); } }
The above is the detailed content of How does a JS subclass use Object.getPrototypeOf to call the parent class?. For more information, please follow other related articles on the PHP Chinese website!