类,构造函数,工厂函数中的澄清需求

cin*_*l45 6 javascript ecmascript-6

我正在玩ES6类,我的最终目标是了解类与构造函数与工厂函数之间的区别。我目前的理解是,构造函数和类基本上使用相同的设计模式,而类只是构造函数的新语法。基于此假设,我试图创建一些示例,以显示类/构造函数与工厂函数之间的对比。

在下面的示例中,我旨在返回新对象和继承的一些方法。

我的第一个示例使用类语法非常简单。

示例#1:

class Person {
    constructor(name, age, location, occupation) {
        this.name = name;
        this.age = age;
        this.location = location;
        this.occupation = occupation;
    }
    printDescription() {
        console.log(`My name is ${this.name} and I'm ${this.age} years old. I live in ${this.location} and I work as a ${this.occupation}.`);
    }
}
const firstUser = new Person('Tom', 30, 'Sydney', 'Teacher');
firstUser.printDescription();
Run Code Online (Sandbox Code Playgroud)

在第二个示例中,我尝试使用不同的方法来复制第一个示例,但是我不确定这是工厂构造函数还是工厂函数。

实施例#2:

function PersonMaker (name, age, location, occupation) {

    let person = {name, age, location, occupation};

    person.printDetails = () => {
        console.log(`My name is ${name} and I'm ${age} years old. I live in ${location} and I work as a ${occupation}.`);
    };

    return person;
}

const secondUser = PersonMaker('Johnny', 25, 'London', 'Driver');
secondUser.printDetails();
Run Code Online (Sandbox Code Playgroud)

我需要澄清第二个示例中使用的模式,如果它不是工厂函数,我如何将其转换为一个?

Pan*_*het 7

因为它返回一个对象,所以它是一个工厂函数 -它已经在那里解释过

构造函数的行为与此不同,它不返回值:

function Person(name, age, location, occupation){
    this.name = name
    this.age = age
    this.location = location
    this.occupation = occupation
}

Person.prototype.printDetails = function(){
        console.log(`My name is ${this.name} and I'm ${this.age} years old. I live in ${this.location} and I work as a ${this.occupation}.`);
};

const secondUser = new Person('Johnny', 25, 'London', 'Driver');
secondUser.printDetails();
Run Code Online (Sandbox Code Playgroud)

我通过将原型扩展为单独的构造函数来使用方法的定义,并且您仍然可以在构造函数内定义方法:

function Person(name, age, location, occupation){
    this.name = name
    this.age = age
    this.location = location
    this.occupation = occupation

    this.printDetails = function(){
        console.log(`My name is ${this.name} and I'm ${this.age} years old. I live in ${this.location} and I work as a ${this.occupation}.`);
    };
}

const secondUser = new Person('Johnny', 25, 'London', 'Driver');
secondUser.printDetails();
Run Code Online (Sandbox Code Playgroud)