1.單繼承,使用call()方法
//父類
function Father(name,age)
{
this.Name = name;
this.Age = age;
this.Intro = function()
{
alert("hello, I am" + this.Name);
}
}
//子類
function Child(name,age)
{
Father.call(this,name,age);//實現繼承!並且調用父類的構造方法,this是當前對象
// Father.apply(this, new Array(name,age)); //跟call一樣的功能
this.Code = function()
{
alert("I am coding");
}
}
var father = new Father("father",50);
var child = new Child("child",23);
father.Intro();
child.Intro(); //子類調用繼承自父類的方法
child.Code(); //子類調用自己的方法
2.單繼承
//父類
function Father(name,age)
{
this.Name = name;
this.Age = age;
this.Intro = function()
{
alert("hello, I am" + this.Name);
}
}
//子類
function Child(name,age)
{
this.Constructer = Father; //指定方法爲上面那個父類的那個方法,跟下面的方法合起來實現繼承
this.Constructer(name,age); //調用該方法:注意調用的時候,是Child對象調用,那麼調用完,Child的2個屬性也就賦值了,而且多了1個方法
delete this.constructor; // 刪除這個方法,是因爲不想覆蓋父類的相關方法和屬性?
this.Code = function()
{
alert("I am coding");
}
}
var father = new Father("father",50);
var child = new Child("child",23);
father.Intro();
child.Intro(); //子類調用繼承自父類的方法
child.Code(); //子類調用自己的方法
3.多繼承
//父類1
function Father(name,age)
{
this.Name = name;
this.Age = age;
this.Intro = function()
{
alert("hello, I am" + this.Name);
}
}
//父類2
function Father_2(pay)
{
this.Pay = pay;
this.showPay = function()
{
alert("your pay is " + this.Pay);
}
}
//子類
function Child(name,age,pay)
{
this.Constructer = Father; //指定方法爲上面那個父類的那個方法
this.Constructer(name,age); //調用該方法:注意調用的時候,是Child對象調用,那麼調用完,Child的2個屬性也就賦值了,而且多了1個方法
delete this.Constructor; // 刪除這個方法,是因爲不想覆蓋父類的相關方法和屬性?
this.Constructer2 = Father_2;
this.Constructer2(pay);
delete this.Constructer2;
this.Code = function()
{
alert("I am coding");
}
}
var father = new Father("father_1",50);
var fater_2 = new Father_2(5000);
var child = new Child("zxh",23,10000); //I am coding.
father.Intro(); //hello, I am father'_1
child.Intro(); //調用從第一個父類繼承的方法 hello,I am zxh.
child.Code(); //I am coding
child.showPay(); //調用從第二個父類繼承的方法 your pay is 10000
4.多繼承2
//父類構造方法
function Father(name,age)
{
this.Name = name;
this.Age = age;
}
//父類的方法
Father.prototype.Intro = function()
{
alert("I am father");
}
//子類構造方法
function Child(name,age)
{
Father.call(this,name,age); //調用父類構造方法,得到各個屬性
}
Child.prototype = new Father(); //實現繼承
//定義子類自己的方法
Child.prototype.Code = function()
{
alert("I am coding !");
}
//覆蓋父類的方法[如果不指定上面的繼承,其實也就相當與自己新定義一個一樣]
Child.prototype.Intro = function()
{
alert("I am " + this.Name);
}
var father = new Father();
var child = new Child("zxh",23);
father.Intro(); //父類調用自身方法
child.Intro(); //子類調用覆蓋父類的方法
child.Code(); //子類調用自己定義的方法