繁体   English   中英

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

[英]Setting child properties with Object.assign in parent

我有以下代码:

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 应用程序中运行上面的代码肯定是有区别的。 反应截图

这是在 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;

很高兴知道。 有人吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM