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

javascript small example on inheritance_javascript skills

WBOY
Release: 2016-05-16 17:33:59
Original
1030 people have browsed it

Copy code The code is as follows:

//Inherit
function Person(name,sex )
{
this.name=name;
this.sex=sex;
}
Person.prototype.sayName=function()
{
alert(this. name);
}
Person.prototype.saySex=function()
{
alert(this.sex);
}
function Worker(name,sex,job)
{
//Inherit the person class
Person.call(this,name,sex) //This here refers to the instance of the Worker class, such as 'W' below, pass W into the Person construct function, at this time W is disguised as this
in the Person constructor this.job=job;
}

//Worker.prototype=Person.prototype;//If the prototype is a negative value, the subclass's sayJob method and the Person parent class will also have a sayJob method, because it is passed by reference

//Change to the following method, the subclass will not affect the parent class:
for(var i in Person.prototype)
{
Worker.prototype[i]=Person.prototype[i] ;
}

Worker.prototype.sayJob=function()
{
alert(this.job);
}

var p=new Person('lisi','male');
//alert(p.sayJob);

var w=new Worker('zhangsan','male','soy sauce');
w.sayName();
w.saySex();
w.sayJob() ;

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