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

js simulation class inheritance small example_javascript skills

WBOY
Release: 2016-05-16 18:22:54
Original
928 people have browsed it
Copy code The code is as follows:

//Use prototypal inheritance, and use temporary objects in the middle as the prototype attribute of Child , the prototype attribute of the temporary object points to the prototype of the parent class,
//Prevents all subclasses and parent class prototype attributes from pointing to the same object.
//In this way, when the prototype attribute of the subclass is modified, it will not Affects other subclasses and parent classes
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F ();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}

function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;}; //Use closure to simulate private members
this.setName = function(value){name=value;};
}
Parent.prototype.print = function(){alert("print!");};
Parent.prototype.hello = function()
{
alert(this.getName() "Parent ")
};

function Child(name,age)
{
Parent.apply(this, arguments);//Call the parent class constructor to inherit the properties defined by the parent class
this.age = age;
}
extend(Child,Parent); //Inherit Parent

Child.prototype.hello = function() //Override the hello method of the parent class
{
alert(this.getName() "Child");

Parent.prototype.hello.apply(this,arguments); //Call the parent class method with the same name
};
//Subclass method
Child.prototype.doSomething = function(){ alert(this.age "Child doSomething"); };

var p1 = new Child("xhan", 22);

var p2 = new Child("xxx",33);

p1.hello();
p2.hello();

p1 .doSomething(); //Subclass method
p1.print(); //Parent class method

alert(p1 instanceof Child); //true
alert(p1 instanceof Parent); //true
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!