【问题标题】:Typescript factory without constructor没有构造函数的打字稿工厂
【发布时间】:2021-03-02 05:37:37
【问题描述】:

我最近遇到了以下代码:

class PizzaMaker {
    create(event: { name: string; toppings: string[] }) {
        return { name: event.name, toppings: event.toppings };
    }
}

const pizzaMaker = new PizzaMaker();

const pizza = pizzaMaker.create({
    name: 'Inferno',
    toppings: ['cheese', 'peppers'],
});

console.log(pizza);
// Output: { name: 'Inferno', toppings: [ 'cheese', 'peppers' ] }

PizzaMaker 在没有构造函数的情况下如何实例化?

【问题讨论】:

    标签: javascript typescript constructor factory


    【解决方案1】:

    在任何支持原生类的环境中(例如 ES6 及更高版本),如果未提供构造函数,则会自动生成:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

    如果您不提供自己的构造函数,则会为您提供默认构造函数。如果您的类是基类,则默认构造函数为空。

    对于不支持原生类的环境(例如 ES5 和之前的版本),TypeScript 会为您生成默认构造函数:

    来自the playground

    class PizzaMaker {
        create(event: { name: string; toppings: string[] }) {
            return { name: event.name, toppings: event.toppings };
        }
    }
    
    

    发出 JavaScript:

    "use strict";
    var PizzaMaker = /** @class */ (function () {
        // Note: this empty function is the default constructor
        function PizzaMaker() {
        }
        PizzaMaker.prototype.create = function (event) {
            return { name: event.name, toppings: event.toppings };
        };
        return PizzaMaker;
    }());
    
    

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 2018-02-12
      • 2018-05-22
      • 1970-01-01
      • 2012-09-29
      • 2016-09-04
      相关资源
      最近更新 更多