1.繼承的實現(xiàn)方式
typescript代碼:
class A{
name: string;
constructor(name){
this.name=name;
}
print(){
console.log(this.name);
}
}
class B extends A{
old: number;
constructor(name,old){
super(name);
this.old=old;
}
out(){
console.log(this.name+this.old);
}
}
let b=new B('jc',1);
b.out();
用tsc編譯后的ES5代碼:
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var A = (function () {
function A(name) {
this.name = name;
}
A.prototype.print = function () {
console.log(this.name);
};
return A;
}());
var B = (function (_super) {
__extends(B, _super);
function B(name, old) {
var _this = _super.call(this, name) || this;
_this.old = old;
return _this;
}
B.prototype.out = function () {
console.log(this.name + this.old);
};
return B;
}(A));
var b = new B('jc', 1);
b.out();
- 可以看出來typescript中類型之間的繼承是通過寄生組合式繼承來完成的,這里可以給出一個寄生組合式繼承的簡單例子:
function extend(B,A){
var prototype=Object.create(A.prototype);
prototype.construtor=B;
B.prototype=prototype;
}
function A(name){
this.name=name;
}
A.prototype.print=function(){
console.log(this.name);
}
A.prototype.num=1;
function B(name,old){
A.call(this,name);
this.old=old;
}
extend(B,A);
B.prototype.ready=function(){
console.log(this.name+this.old);
}
寄生組合式繼承的基本思路是:不必為了制定子類型的原型來調(diào)用父類型的構(gòu)造函數(shù)诱告,只需要將父類型的原型對象的副本賦給子類型的原型對象垦写,然后修正一下原型對象的構(gòu)造函數(shù)指向臭笆。
2.私有變量的實現(xiàn)方式
typescript代碼:
class A{
private name: string;
constructor(name){
this.name=name;
}
print(){
this.console();
}
private console(){
console.log(this.name);
}
}
let a=new A('jc');
a.print();
tsc編譯后的代碼:
var A = (function () {
function A(name) {
this.name = name;
}
A.prototype.print = function () {
this.console();
};
A.prototype.console = function () {
console.log(this.name);
};
return A;
}());
var a = new A('jc');
a.print();
可以看到typescript并沒有為私有屬性和函數(shù)做任何處理缭裆,但是如果在外部訪問了私有變量底挫,在編譯時會報錯,可見typescript是在編譯過程的底層實現(xiàn)了對私有變量的檢查淑际。
3.靜態(tài)變量的實現(xiàn)方式
typescript代碼:
class A{
static num: number=1;
}
console.log(A.num);
tsc編譯后的代碼:
var A = (function () {
function A() {
}
return A;
}());
A.num = 1;
console.log(A.num);
可見靜態(tài)變量時與類有關(guān)的變量畏纲,所以可以直接將該屬性賦給構(gòu)造函數(shù)對象,讓其成為構(gòu)造函數(shù)的屬性春缕,在類的內(nèi)部也要通過類名才能訪問到靜態(tài)變量盗胀。
- red