gpt4 book ai didi

javascript - 类与构造函数与工厂函数中的澄清需要

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:13 25 4
gpt4 key购买 nike

我正在研究 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();

对于第二个示例,我试图用不同的方法复制第一个示例,但我不确定这是工厂构造函数还是工厂函数。

示例 #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();

我需要阐明第二个示例中使用的模式,如果它不是工厂函数,我如何将它变成工厂函数?

最佳答案

因为它返回一个对象,它是一个工厂函数 - it's already explained there .

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

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();

我通过扩展原型(prototype)来使用方法的定义只是为了分离构造函数,你仍然可以在构造函数中定义一个方法:

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();

关于javascript - 类与构造函数与工厂函数中的澄清需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com