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.
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.
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
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();
}
}