JavaScript implements a simple example of inheritance _javascript tips

Source: Internet
Author: User

As an object-oriented language, then the inheritance of nature is a big feature, the following is a very simple code example, it demonstrates the rationale for inheritance, interested or just want to learn this aspect of friends can refer to, hope to be able to help the group.

Inherited
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 person class 
 Person.call (this,name,sex)//Here This refers to an instance of the Worker class, As in the following ' W ', the W is passed into the person constructor, and W is disguised as this
 this.job=job
in the person constructor. worker.prototype=person.prototype;//if such a negative stereotype is used, the subclass's Sayjob method person parent class also has a Sayjob method, because the subclass does not affect the parent class because it is a reference pass
//change to the following way: 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 ();

The above mentioned is the entire content of this article, I hope you can enjoy.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.