javascript类式继承2

 与javascript类式继承1不同的是,在2中的extend扩展了一个superClass属性,为了降低子类对父类的耦合度,
在1中Author要想继承父类的属性必须使用Person.call(this,[argument])方法,这样会导致子类对父类的高耦合
在2中我们改写Author的构造函数,并使用extend中定义的superClass属性,Author.superClass.constructor.call(this,[argument])来继承父类的属性。
代码12行中是对父类构造是否指向正确的判断。
 1 (function () {
 2 
 3     function extend(subClass, superClass) {
 4         function f() {
 5         }
 6 
 7         f.prototype = superClass.prototype;
 8         subClass.prototype = new f();
 9         subClass.prototype.constructor = subClass;
10 
11         subClass.superClass = superClass.prototype;
12         if (superClass.prototype.constructor == Object.prototype.constructor) {
13             superClass.prototype.constructor = superClass;
14         }
15     }
16 
17     function Person(age) {
18         this.age = age;
19     }
20 
21     Person.prototype.getAge = function () {
22         return this.age;
23     }
24 
25     function Author(age, books) {
26         Author.superClass.constructor.call(this, age);
27         this.books = books;
28     }
29 
30     extend(Author, Person);
31     var a1 = new Author(21, "asd");
32     console.log(a1.getAge());
33 
34 
35 })()
原文地址:https://www.cnblogs.com/qiutiantian/p/3156535.html