[TOC] #### 1. 工廠函數(shù)創(chuàng)建對(duì)象 --- 當(dāng)我們有多個(gè)變量的結(jié)構(gòu)非常類似時(shí),如下所示,反復(fù)書寫結(jié)構(gòu)過于麻煩,我們可以定義一個(gè)工廠函數(shù)來創(chuàng)建對(duì)象 ```javascript let object1 = { name: "jia", add(x, y) { return x + y; } } let object2 = { name: "wang", add(x, y, z) { return x + y + z; } } console.log(object1.add(1, 2)) console.log(object2.add(1, 2, 3)) ``` 使用工廠函數(shù)創(chuàng)建對(duì)象 ```javascript function factory(name = '') { return { name, add(...args) { return args.reduce((sum, item) => sum + item, 0) } } } console.log(factory('jia').add(1, 2)) console.log(factory('wang').add(1, 2, 3)) ``` #### 2. 使用構(gòu)造函數(shù)創(chuàng)建對(duì)象 --- ```javascript function User(name) { this.name = name this.show = function () { console.log(`my name is ${name}`) } // 函數(shù)被實(shí)例化時(shí) // 如果沒有定義 return 時(shí),默認(rèn)值為 this // return this // 當(dāng)然,如果不想返回 this 可以自定義返回值 // return {} } const person = new User('liang') person.show() ``` 在 js 中,絕大多數(shù)的數(shù)據(jù)類型都是通過構(gòu)造函數(shù)創(chuàng)建的 在瀏覽器控制臺(tái)輸出一個(gè)對(duì)象,可以看到這個(gè)對(duì)象是通過構(gòu)造函數(shù) Object 創(chuàng)建的 ![](https://img.itqaq.com/art/content/00b47f0753289eb01ce4592e8fba6c86.png) 所以,我們可以這樣來定義對(duì)象: ```javascript const obj = new Object() const obj = new Object({ name: "liang" }) const count = new Number(100) const string = new String('liang') const bool = new Boolean(true) const date = new Date() const regexp = new RegExp(/\d{3,}/) const fun = new Function('cms', `console.log('this is function')`) ```