Home > Web Front-end > JS Tutorial > body text

JavaScript subclasses use Object.getPrototypeOf to call parent class method analysis_javascript skills

WBOY
Release: 2016-05-16 17:10:33
Original
820 people have browsed it

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

Copy code 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(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 (implemented by Firefox/Chrome) to obtain the prototype of the object. It can be used to imitate Java's super.

Copy code 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 hanging on this in the subclass Man calls the method1 hanging on this in the parent class Person, and the m2 hanging on the prototype The method 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 like this in Java

Copy code 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();
}
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!