SoFunction
Updated on 2025-04-09

JavaScript subclasses are used to call parent class methods to parse

Each function has a prototype attribute called a prototype. Each object also has a prototype. It can be accessed through __proto__ in Firefox/Safari/Chrome/Opera. There is no relevant interface provided in IE6/7/8.

Copy the codeThe code is as follows:

function Person(){
    this.method1 = function(){}
}
.method2 = function(){}

function Man(){}
= new Person();

.m1 = function(){}
.m2 = function(){}

var m = new Man();
for(var a in m.__proto__){
    alert(a);
}

Defines the parent class Person and the child class Man. new a Man object and print out all properties.

ECMAScript V5 adds a static getPrototypeOf method (Firefox/Chrome implemented) to Object to get the prototype of the object. Use it to imitate Java's super.

Copy the codeThe code is as follows:

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

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

.m2 = function(){
    (this).method2();
}

 
var man = new Man();
man.m1();
man.m2();

The method hanged on this in the subclass Man calls method 1 on this in the parent class Person, and the method hanged on the prototype calls method 2 on the parent class prototype.

As shown above, it can be seen that the object prototype not only includes the properties on its constructor 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 well in the subclass, and it requires some skills to complete it.

This is how it is in Java

Copy the codeThe code is as follows:

package bao1;

class Person {
    private String name;

    Person(String name) {
        = name;
    }
    public void method1() {
        ();
    }
}
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();
    }
}