js继承摘要
对象的构造函数是指向创建对象的类的原型对象的构造函数。
类是一个Function, Function都有原型对象,原型对象的构造函数指向类的声明。
function Person(){ } Person.prototype.constructor === Person //true var p1 = new Person(); p1.constructor === Person //true
a.prototype = {} 等价于 a.prototype = new object({});
此时 a.prototype.constructor 指向错误, 指到了object上
应该修正: a.prototype.constructor = a
原型继承typescript代码:
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));