Typescript中class的extends码源分析
生活随笔
收集整理的這篇文章主要介紹了
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?
轉載于:https://www.cnblogs.com/wangtingnoblog/p/10390699.html
總結
以上是生活随笔為你收集整理的Typescript中class的extends码源分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Lintcode]115. Uniqu
- 下一篇: MySQL--Delete语句别名+LI