復制代碼 代碼如下:
//繼承
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();