gpt4 book ai didi

javascript - 在声明文件中描述 mixins

转载 作者:行者123 更新时间:2023-11-28 03:50:21 25 4
gpt4 key购买 nike

假设您要为其创建类型的现有 Javascript 框架。 Javascript 代码使用 Node.js 模块、原型(prototype)继承和 mixins:

// File: src/lib/a.js

function A() {
this.isA = true;
this.type = 'a';
}

module.exports = A;

// File: src/lib/b.js

var A = require('./a');
var plugin = require('./plugin');

function B() {
A.call(this);
this.isB = true;
this.type = 'b';
plugin(this);
}

B.prototype = object.create(A.prototype);
B.prototype.constructor = B;

module.exports = B;

// File: src/lib/plugin.js

function plugin(obj) {
obj.doSomethingFancy = function() {
// ...
}
}

module.exports = plugin;

您将如何在声明文件中描述 B,以便它传达某些成员是由/通过其构造函数创建的?

最佳答案

您真的需要这种区别吗?您的构造函数始终创建这些成员,因此如果您有一个 B 类型的对象 - 您可以确定这些属性将存在。

如果您想表明某个成员可能不存在 - 请在其名称后加上 ? 后缀,就像我在下面的示例中为 doSomethinFancy 所做的那样。

class A {
public isA: boolean;
public type: string;

constructor() {
this.isA = true;
this.type = 'a';
}
}

function plugin(obj: any): any {
obj.doSomethingFancy = function() {
// ...
}
}

class B extends A {
public isB: boolean;

// same could be used for optional function arguments
public doSomethingFancy?: () => {};

constructor() {
super();
this.isB = true;
this.type = 'b';
plugin(this);
}
}

关于javascript - 在声明文件中描述 mixins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042226/

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