javascript中最常用的继承模式 组合继承

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript中最常用的继承模式 组合继承

  2020-05-12 我要评论
复制代码 代码如下:

<script type="text/javascript">
//创建基类
function Person(name, age) {
this.name = name;
this.age = age;
}
//通过原型方式给基类添加函数(这样可以服用此函数)
Person.prototype.showName = function () {
alert(this.name);
}
//创建子类
function Student(name, age, score) {
this.score = score;
Person.call(this,name,age);
}
//把父类的实例赋值给子类的原型
Student.prototype = new Person();
//通过原型方式给子类添加函数(这样可以服用此函数)
Student.prototype.showScore = function () {
alert(this.score);
}

//以下为使用
var student = new Student("zhangsan", 22, 100);
student.showName();
student.showScore();

var stu = new Student("lisi", 25, 200);
stu.showName();
stu.showScore();
</script>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们