# [JavaScript] 建構子 / 工廠函式(factory function)創造物件? ###### tags: `前端筆記` ## 只是粗略談 1. 建構子是以 `prototype` 將自己的東西丟給物件「繼承」,除非物件自己改寫,要不然物件本身沒有繼承來的東西(在 `prototype` 裡面) 2. 工廠函式(factory function)則是以閉包(closure)為基準,不過創造出來的物件自己「都會有全部的東西」 ### 工廠函式(factory function) ```javascript= // 用閉包的觀念使用 Factory Function 建立物件 // 但是就會變成每個物件都有「自己的」方法,而不是「繼承」 // 但好處就是不用管 this 跟 prototype chain const Person = (name) => { const sayName = () => console.log(`my name is ${name}`) return {sayName} }; const Nerd = (name) => { // simply create a person and pull out the sayName function with destructuring assignment syntax! // 因為回傳的是物件方法,所以在變數那邊用 {} 讓其退回成「函式」 const {sayName} = Person(name) const doSomethingNerdy = () => console.log('nerd stuff') return {sayName, doSomethingNerdy} }; const jeff = Nerd('jeff'); jeff.sayName(); //my name is jeff jeff.doSomethingNerdy(); // nerd stuff ``` ![](https://i.imgur.com/FRfCNYY.png) ### 建構子 ```javascript= 也可以用一開始的建構子,但這樣子就要記得 this 的處理 function Person (name) { this.name = name; } Person.prototype.sayName = function () { console.log(`My name is ${this.name}`); }; Person.prototype.doSomethingNerdy = function () { console.log('nerd stuff'); }; const jeff = new Person('jeff'); jeff.doSomethingNerdy(); // nerd stuff ``` ![](https://i.imgur.com/Olh7DZp.png) ## 推薦資源 1. [JavaScript object creation patterns tutorial - factory , constructor pattern, prototype pattern ](https://www.youtube.com/watch?v=xizFJHKHdHw&t=594s) 2. [Why use "closure"?](http://howtonode.org/why-use-closure)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up