The JavaScript subclass calls the superclass method with object.getprototypeof

  • 2020-03-30 00:44:07
  • OfStack

Each function has a prototype property called a prototype. Each object has a prototype, Firefox/Safari/Chrome/Opera can access through __proto__, IE6/7/8 did not provide relevant interface.

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__){ 

It defines the superclass Person, subclass Man. New, an object of Man, prints out all the properties.

ECMAScript V5 adds a static getPrototypeOf method (implemented in Firefox/Chrome) to the Object to get the prototype of the Object. You can use it to emulate Java's super.

function Person(){ 
    this.method1 = function(){alert(1)} 
Person.prototype.method2 = function(){alert(2);} 

function Man(){ 
    this.m1 = function(){ 
Man.prototype = new Person();//Prototype inheritance

Man.prototype.m2 = function(){ 

var man = new Man(); 

Method m1 hung on this in subclass Man calls method1 hung on this in superclass Person, and method m2 hung on prototype calls method2 on superclass prototype.

As you can see above, an object prototype includes not only the properties on its constructor prototype, but also the properties on this in the constructor. Of course, because of the context in JavaScript, the this in the parent class does not translate well in the subclass automatically, which takes some tricks to do.

This is true in Java

package bao1; 

class Person { 
    private String name; 

    Person(String name) { = name; 
    public void method1() { 
class Man extends Person{ 

    Man(String name) { 
    public void m1() { 
public class Test { 
    public static void main(String[] args) {         
        Man man1 = new Man("Jack"); 

Related articles: