[英]understanding typescript inheritance
我的问题灵感来自这个问题
这是打字稿继承代码
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; }
__.prototype = b.prototype;
d.prototype = new __();
};
我将版本简化为这个版本
function extend(Destination, Base) {
function Hook() { this.constructor = Destination; }
Hook.prototype = Base.prototype;
var hook = new Hook();
Destination.prototype = hook;
};
我从这里绘制了图形表示:
你能确认或更正图形表示吗?
我特别不明白这部分:
function Hook() { this.constructor = Destination; }
你能告诉我继承是如何处理参数和附带的例子的吗
这是任何帮助,我已经根据当前的__extends
函数注释了每一行以说明它的作用(它与您的示例略有不同)
var extend = function (subType, superType) {
// Copy superType's own (static) properties to subType
for (var property in superType) {
if (superType.hasOwnProperty(property)) {
subType[p] = superType[p];
}
}
// Create a constructor function and point its constructor at the subType so that when a new ctor() is created, it actually creates a new subType.
function ctor() {
this.constructor = subType;
}
if(superType === null) {
// Set the subType's prototype to a blank object.
subType.prototype = Object.create(superType);
} else {
// set the ctor's prototype to the superType's prototype (prototype chaining)
ctor.prototype = superType.prototype;
// set the subType's prototype to a new instance of ctor (which has a prototype of the superType, and whos constructor will return a new instance of the subType)
subType.prototype = new ctor();
}
};
请注意, __extends
可能会在不久的将来再次更改以包含Object.setPrototypeOf(...);
的使用Object.setPrototypeOf(...);
GitHub -更改类继承代码
当我综合我的问题和这个答案以及@series0ne 的答案时
这是我从打字稿继承中了解到的:
函数 ctor() 的作用是:
如链接的答案:
Car.prototype.constructor = Car;
它是等价的
subType.prototype.constructor = subType
它提供:
subType.constructor === subType -> true
为了
ctor.prototype = superType.prototype;
subType.prototype = new ctor();
它是等价的
Car.prototype = new Vehicle(true, true);
这确保
subType.prototype = new superType();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.