Home  >  Article  >  Web Front-end  >  A simple example of inheritance in javascript_javascript skills

A simple example of inheritance in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:49:00911browse

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

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

Statement:
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