javascript - 在父级中使用 Object.assign 设置子属性

标签 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}
Object.assign在父类中不设置子类中的任何属性。我不想为每个调用 super 和另一个 Object.assign 的子类指定一个构造函数.

是否有某种方法可以使用父类中的单个方法为子类分配所有属性,而无需明确指定每个属性?

最佳答案

在 Node 和 React 应用程序中运行上面的代码肯定是有区别的。
screenshot from 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" }));

这是在浏览器中运行的 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"
}));

我也不知道为什么 webpack 这样做
this.child = void 0;

很高兴知道。有人吗?

关于javascript - 在父级中使用 Object.assign 设置子属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55639419/

相关文章:

PHP jQuery .post .get,这是正确的方法吗?

javascript - YouTube视频无法在jQuery中使用

typescript - Koa + typescript : Property 'body' does not exist on type Request

PHP文件上传状态

javascript - 在 for 循环中输出 javascript 数组值会导致未定义

javascript - 配置 WebStorm/PhpStorm 将 .ts 文件编译为 .js 到 "js"文件夹

javascript - 如何将 typescript 类型的字符串转换为字符串数组?

d3.js - D3.js 组件中的样式不以 Angular 2 显示

javascript - 在 Google 图表中启用/禁用图例及其对应的行 onclick

node.js - Typescript 版本与 Node 版本