gpt4 book ai didi

javascript - 理解 typescript 继承

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:08 25 4
gpt4 key购买 nike

我的问题的灵感来自this question

这是 typescript 继承代码

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;
};

我绘制图形表示的灵感来自 here :

enter image description here

您能确认或更正文字表示吗?
我特别不明白这部分:

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(...);

GitHub - Change Class Inheritance Code

关于javascript - 理解 typescript 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com