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

A simple example of inheritance in javascript_javascript skills

WBOY
Release: 2016-05-16 15:49:00
Original
939 people have browsed it

As an object-oriented language, inheritance is naturally a major feature. The following is a very simple code example, which demonstrates the basic principles of inheritance. Friends who are interested or want to learn this aspect can refer to it. , I hope I can help everyone.

//继承
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)
{
 //继承person类 
 Person.call(this,name,sex) //这里的this指的是Worker类的实例,如下面的'W' ,把W传入Person构造函数,这时W伪装成Person构造函数里的this
 this.job=job;
}
//Worker.prototype=Person.prototype;//如果这样负值原型,子类的sayJob方法Person父类也会有sayJob方法,因为是引用传递
//改成如下方式则子类不会影响父类:
for(var i in Person.prototype)
{
 Worker.prototype[i]=Person.prototype[i];
}
Worker.prototype.sayJob=function()
{
 alert(this.job);
}
var p=new Person('lisi','男');
//alert(p.sayJob);
var w=new Worker('zhangsan','男','打酱油的');
w.sayName();
w.saySex();
w.sayJob();
Copy after login

The above is the entire content of this article, I hope you all like it.

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!