javascript中最常用的继承模式 组合继承
更新时间:2010年08月12日 11:05:27 作者:
组合继承避免了原型链和借用构造函数的缺陷,成为JavaScript中最为常用的继承模式
复制代码 代码如下:
<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>
相关文章
javascript 面向对象编程 function是方法(函数)
在进行编程时,必免不了要碰到复杂的功能。初学者最怕复杂的功能,因为不能够很好的进行功能边界划分,只能一大串if、循环加case堆叠在一起,结果出来的程序自己看着晕,别人看着更晕。2009-09-09


最新评论