Typescript中class的extends码源分析

学习typescript的乐趣在于看它的码源是如何要js实现的、

今天要分析的是类继承的码源。我们先来看一下使用ES5的组合继承是如何做到的:

 1 function Person(name) {
 2     this.name = name;
 3 }
 4 Person.prototype.sayName = function () {
 5     console.log(this.name);
 6 };
 7 function Student(name, school) {
 8     Person.call(this, name)
 9     this.school = school;
10 }
11 Student.prototype = Person.prototype;
12 Student.prototype.saySchool = function () {
13     console.log(this.school);
14 };
15 let student = new Student('wangting', 'NT');
16 console.log('school' in student);
17 console.log('saySchool' in student);
18 console.log('name' in student);
19 console.log('sayName' in student);

再来看一下typescript的实现:

 1 var __extends = (this && this.__extends) || (function () {
 2     var extendStatics = 
 3         Object.setPrototypeOf ||
 4         ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
 5         function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
 6     return function (d, b) {
 7         // 类属性和类方法的继承
 8         extendStatics(d, b);
 9 
10         function __() { this.constructor = d; }
11         // d的原型对象
12         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13     };
14 })();
15 var Person = (function () {
16     function Person(name) {
17         this.name = name;
18     }
19     Person.prototype.sayName = function () {
20         console.log(this.name);
21     };
22     Person.Country = 'China';
23     return Person;
24 }());
25 var Student = (function (_super) {
26     __extends(Student, _super);
27     function Student(name, school) {
28         var _this = _super.call(this, name) || this;
29         _this.school = school;
30         return _this;
31     }
32     Student.prototype.saySchool = function () {
33         console.log(this.school);
34     };
35     return Student;
36 }(Person));
37 var student = new Student('wangting', 'NT');
38 console.log(Student.Country); // China
39 student.saySchool(); // NT
40 student.sayName(); // wangting

猜你喜欢

转载自www.cnblogs.com/wangtingnoblog/p/10390699.html