企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## 创建对象的方式 ### 1. 工厂模式 -- 创建多个类似的对象 ``` function createPersion(name, age, job) { let o = new Object() o.name = name o.age = age o.job = job o.sayName = function() { console.log(this.name) } return o } let persion1 = createPersion('xx', '18', 'codder') ``` ### 2. 构造函数模式 * 内部没有显示创建对象 * 属性和方法直接赋值给this * 没有return ``` function Persion(name, age, job) { this.name = name this.age = age this.job = job this.sayName = function() { console.log(this.name) } } let persion1 = new Persion('xx', '18', 'codder') ``` #### 构造函数创建对象遇到的问题 构造函数内部创建的函数,会在每个实例上都创建一遍 ``` function Persion(name, age, job) { this.name = name this.age = age this.job = job this.sayName = new Function("console.log(this.name)") } ``` 这样会造成两个Persion实例中,相同的功能,不同的Function实例。 ##### 如何解决 函数定义转移到构造函数外部 ``` function Persion(name, age, job) { this.name = name this.age = age this.job = job this.sayName = sayName } function sayName() { console.log(this.name) } ``` 遇到的问题:污染全局,不好维护 ### 3. 原型模式 -- 属性和方法定义在原型上,开发中通常不单独使用原型模式 * 每个函数都有一个 prototype 属性 ![](https://img.kancloud.cn/95/be/95be3f699308f3347db619c3064289c1_1502x378.png) ``` function Persion() {} Persion.prototype = name = 'tom' Persion.prototype.age = 18 Persion.protytype.sayName = function() {...} let persion1 = new Persion() persion1.sayName() ``` 遇到的问题: * 不能通过传参赋值 * 共享数据的问题 例如: ``` function Persion(){} Persion.protytype.name = [1, 2] let persion1 = new Persion() let persion2 = new Persion() persion1.name.push(3) console.log(persion1.name) // [1,2,3] console.log(persion2.name) // [1,2,3] ``` ![](https://img.kancloud.cn/77/e7/77e7ef58feab71d11b2c412aa953d7f5_1491x466.png)