Javascrip: a small example of inheritance. For more information, see
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) // here this refers to the instance of the Worker class, 'w' below, pass w to the Person constructor, in this case, W is disguised as this in the Person constructor.
This. job = job;
}
// Worker. prototype = Person. prototype; // if such a negative value is prototype, the sayJob method of the subclass, the Person parent class, also has the sayJob method, because it is a reference Transfer
// If it is changed to the following method, the Child class 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 ('hangsan', 'male', 'soy sauce ');
W. sayName ();
W. saySex ();
W. sayJob ();