# 章序号/节序号/节/笔记序号
- Objective:批量创建对象
# 概念阐释
## 语义
工厂函数,用于创建对象的函数,用一组对象‘模板’来生产不同参数的对象。就像是一张Excel表格,标题为工厂函数,设置了一些属性名称,表格内的内容是属性值。
## 语法
```js
const functionName = (property1,property2,object3) => {
//返回一个对象
return {
property1:property1,
property2:property2,
object3(){}
}
};
```
# 举例子


- 属性可以有更**简洁**的写法
```js
const monsterFactory = (name, age) => {
return {
name,
age
}
};
```
## 对象中的方法作为工厂函数的参数
```js
function createPerson(name, age, greetingFunction) {
return {
name: name,
age: age,
greet: greetingFunction
};
}
function formalGreeting() {
console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
function casualGreeting() {
console.log("Hey, I'm " + this.name + " and I'm " + this.age + " years old.");
}
const person1 = createPerson("Alice", 30, formalGreeting);
const person2 = createPerson("Bob", 25, casualGreeting);
person1.greet(); // Hello, my name is Alice and I am 30 years old.
person2.greet(); // Hey, I'm Bob and I'm 25 years old.
```
# 类比、比较与对比
# 问题
🌟🌟🌟🌟
- [练习题](https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/factory-functions)
1. 创建一个名为`robotFactory`的工厂函数,有两个参数`model`和`mobile`。使函数返回一个对象。在对象中,添加一个名为model的键,并将值设为model参数。添加另一个属性,键为mobile,值为mobile参数。然后添加一个名为`beep`的方法,没有参数,将日志`“Beep Boop”`记录到控制台中。
1. 使用你的工厂函数,声明一个名为`tinCan`的`const`变量。将`robotFactory`的第一个参数设置为`'P-500'`,第二个参数设置为`true`,并将返回值赋值给`tinCan`。
2. 分别返回model、mobile的参数
3. 尝试用`tinCan`返回beep的参数,这说明什么?
# 问题答案
```js
const robotFactory = (model,mobile,beep) => {
return {
model: model,
mobile: mobile,
beep(){
return 'Beep Boop';
}
}
};
//生成一种叫tinCan的机器人,它的属性值为:
const tinCan = robotFactory('P-500',true,);
console.log(tinCan.beep());
console.log(tinCan.model);
```
# 备注(经验集/错误集)
## 错误
- 返回一个对象的语法:
```js
return {
model,
mobile,
}
```
- `tinCan.beep()`之所以能返回`Beep Boop`是因为`robotFactory`是函数的原因。
## summary
解决的怎么样?
## 参考资料