在js中,子类如何调用父类中方法?如下图示:

JavaScript012

在js中,子类如何调用父类中方法?如下图示:,第1张

//子类Student

function Student(name,age,sex,phone){

//继承方法

Person.call(this,name,age)

//添加自己的属性

this.sex=sex

this.phone=phone

//添加自己的方法

this.say()

}

//继承父类的属性

for(var i in Person.prototype){

Student.prototype[i]=Person.prototype[i]

}

//重写父类方法

Student.prototype.say()

{

alert(this.phone+' 'this.sex)

}

很少用继承,简单举个例子好了。

<script>

Animal.prototype.speak = function(){

console.log("我叫:"+this.name+" 叫声是:"+this.yell)

}

function Animal(name,yell){//动物类(祖父类)

this.name=name

this.yell = yell

}

//---------------------------------------------------

Felidae.prototype = new Animal()

Felidae.prototype.constructor = Felidae

function Felidae(name,yell){//猫科(父类)

Animal.call(this,name,yell)

}

//---------------------------------------------------

ManchurianTiger.prototype = new Felidae()

ManchurianTiger.prototype.constructor = ManchurianTiger

function ManchurianTiger(name,yell){//东北虎(子类)

Felidae.call(this,name,yell)

}

//---------------------------------------------------

var tiger = new ManchurianTiger("虎子","吼吼~")

tiger.speak()

</script>

运行结果:我叫:虎子 叫声是:吼吼~