如何将 javascript 类构造函数参数动态映射到实例属性

Ma *_*obi 2 javascript oop class node.js

我正在构建一个 Node.js 应用程序(Node v10.11.0)并希望在不使用 Typescript 的情况下以 OOP 方式完成它。所以我建立了一些这样的类:

class Component {
  constructor(param1, param2, param3) {
    this.param1= param1;
    this.param2 = param2;
    this.param3 = param3;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想知道 javascript 中是否有一种方法可以自动映射构造函数的参数,而无需this.param1 = param1为每个构造函数参数编写。

我已经尝试过arguments用这样的东西跑过对象:

constructor(param1, param2, param3) {
  Array.from(arguments).forEach(arg => {
    this[arg] = arg;
  }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。这种方法的结果是:

console.log(new Component("arg1", "arg3", "arg3"))

// Component { arg1: "arg1", arg2: "arg2", arg3: "arg3" }
// I want to have this:
// Component { param1: "arg1", param2: "arg2", param3: "arg3" }
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 7

如果您希望构造函数接受离散参数,那么没有什么比您已经在进行的单个赋值更好的了,至少目前是这样。

你可以让构造函数接受一个对象,这样你就可以这样做:

constructor(args) {
    Object.assign(this, args);
}
Run Code Online (Sandbox Code Playgroud)

你这样称呼它:

new Component({param1: "arg1", param2: "arg2", param3: "arg3"});
Run Code Online (Sandbox Code Playgroud)

但是如果它只有一到三个参数,那就是在每个调用点创建额外的工作,而不是在构造函数代码中一次,而且构造函数代码不太清楚。

第三种选择是接受休息参数:

constructor(...args) {
    ["param1", "param2", "param3"].forEach((name, index) => {
        this[name] = args[index];
    });
}
Run Code Online (Sandbox Code Playgroud)

您以正常方式调用它,但再次虽然它是主观的,但对我来说可读性受到损害。


顺便提一下,我想您可能知道,TypeScript 具有此功能。现在使用 TypeScript(它编译为 JavaScript 以在浏览器上使用)越来越普遍。TypeScript 与 Angular 无关,您可以将它用于几乎任何框架(或没有)。

例如在 TypeScript 中:

// TypeScript
class Component {
    constructor(
        public param1: string,
        public param2: string,
        public param3: string
    ) {
    }
}
Run Code Online (Sandbox Code Playgroud)

构造函数中根本不需要任何代码,TypeScript 会自动将这些参数值分配给这些公共属性。(您也可以使用privateprotected。)

  • @MaKobi - 我应该注意到,按照惯例,一旦您超过了三个参数(或者可能多达四个或五个),就应该切换到选项对象,而不是像上面的第一个示例那样。主要不是为了减少构造函数中的代码,而是为了使调用站点上的事情变得简单。 (2认同)