多层继承
作者:学生 最后修改日期:2016-01-08
版权声明:本文为原创内容,转载请声明出处。
原文地址:http://www.excelib.com/article/244/show
原文地址:http://www.excelib.com/article/244/show
function的prototype属性是object类型的属性对象,他本身也可能是使用function创建出来的对象,使用这种方式就可以实现多层继承,比如下面的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function log(msg){ console.log(msg); } function Person(){} Person.prototype.logPerson = function () { log( "person" ); } function Teacher(){ this .logTeacher = function () { log( "teacher" ); } } Teacher.prototype = new Person(); Teacher.prototype.logPrototype = function () { log( "prototype" ); } var teacher = new Teacher(); teacher.logTeacher(); teacher.logPrototype(); teacher.logPerson(); |
这里Teacher的prototype属性是Person创建的实例对象,而使用Teacher创建出来的teacher对象可以调用Teacher的prototype属性对象的属性,所以teacher对象就可以调用Person创建的实例对象的属性,而Person创建的实例对象又可以调用Person的prototype属性对象中的属性,所以teacher对象也可以调用Person的prototype属性对象中的属性方法logPerson,另外,我们给Teacher的prototype属性对象添加了logPrototype方法,所以teacher也可以调用logPrototype方法,最后输出的结果如下
1 2 3 | teacher prototype person |
这种调用方法就相当于基于类语言中的多层继承,他的结构如下图所示
图1
Teacher创建出来的teacher对象在调用属性时会首先在自己的属性中查找,如果找不到就会到Teacher的prototype属性对象的属性中查找,如果还找不到就会到Person的prototype属性对象的属性中查找,而且Teacher的prototype是由两部分组成的,一部分是用Person创建的person对象,另一部分是直接定义的logPrototype方法属性。