ran*_*dyr 5 javascript typescript
我有以下代码:
export class A {
parent?: string;
constructor(attrs: object = {}) {
Object.assign(this, attrs);
}
}
export class B extends A {
public child?: string;
}
console.log(new B({parent: "1", child: "2"}));
// Results in:
// Object {parent: "1", child: undefined}
Run Code Online (Sandbox Code Playgroud)
父类中的Object.assign不会设置子类中的任何属性。我不想为每个调用 super 和 another 的子类指定一个构造函数Object.assign。
是否有某种方法可以使用父类中的单个方法来分配子类上的所有属性,而不必显式指定每个属性?
在 Node 和 React 应用程序中运行上面的代码肯定是有区别的。

这是在 Node 中运行的编译代码(工作正常):
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.A = void 0;
class A {
constructor(attrs = {}) {
Object.assign(this, attrs);
}
}
exports.A = A;
class B extends A {
}
console.log(new B({ parent: "1", child: "2" }));
Run Code Online (Sandbox Code Playgroud)
这是在浏览器中运行的 webpack 代码(未按预期工作)。
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return A; });
class A {
constructor(attrs = {}) {
this.parent = void 0;
Object.assign(this, attrs);
}
}
class B extends A {
constructor(...args) {
super(...args);
this.child = void 0;
}
}
console.log(new B({
parent: "1",
child: "2"
}));
Run Code Online (Sandbox Code Playgroud)
我也不知道为什么webpack要这样做
this.child = void 0;
Run Code Online (Sandbox Code Playgroud)
很高兴知道。有人吗?
| 归档时间: |
|
| 查看次数: |
1704 次 |
| 最近记录: |