對象的構造函數是指向建立對象的類的原型對象的構造函數。typescript
類是一個Function, Function都有原型對象,原型對象的構造函數指向類的聲明。函數
function Person(){ } Person.prototype.constructor === Person //true var p1 = new Person(); p1.constructor === Person //true
a.prototype = {} 等價於 a.prototype = new object({});this
此時 a.prototype.constructor 指向錯誤, 指到了object上spa
應該修正: a.prototype.constructor = aprototype
原型繼承typescript代碼:code
class Person { constructor(private name: string) { } getName() { return this.name; } } class Employee extends Person { constructor(name: string, private age: number) { super(name); } getAge() { return this.age; } }
對應的js代碼:對象
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Person = (function () { function Person(name) { this.name = name; } Person.prototype.getName = function () { return this.name; }; return Person; }()); var Employee = (function (_super) { __extends(Employee, _super); function Employee(name, age) { _super.call(this, name); this.age = age; } Employee.prototype.getAge = function () { return this.age; }; return Employee; }(Person));