- The Node Craftsman Book
- Manuel Kiessling
- 291字
- 2021-07-02 23:36:52
Using a simple function to create plain objects
In our first example, we created a plain myCar object out of thin air – we can simply wrap the creation code into a function, which gives us a very basic object creator:
var makeCar = function() { var newCar = {}; newCar.honk = function() { console.log('honk honk'); }; };
For the sake of brevity, the drive function has been omitted.
We can then use this function to mass-produce cars:
var makeCar = function() { var newCar = {} newCar.honk = function() { console.log('honk honk'); }; return newCar; }; myCar1 = makeCar(); myCar2 = makeCar(); myCar3 = makeCar();
One downside of this approach is efficiency: for every myCar object that is created, a new honk function is created and attached – creating 1,000 objects means that the JavaScript interpreter has to allocate memory for 1,000 functions, although they all implement the same behaviour. This results in an unnecessarily high memory footprint of the application.
Secondly, this approach deprives us of some interesting opportunities. These myCar objects don't share anything – they were built by the same creator function, but are completely independent from each other.
It's really like with real cars from a real car factory: They all look the same, but once they leave the assembly line, they are totally independent. If the manufacturer should decide that pushing the horn on already produced cars should result in a different type of honk, all cars would have to be returned to the factory and modified.
In the virtual universe of JavaScript, we are not bound to such limits. By creating objects in a more sophisticated way, we are able to magically change the behaviour of all created objects at once.
- 電腦組裝與系統(tǒng)安裝
- PLC控制程序精編108例
- 精解Windows 8
- Linux網(wǎng)絡(luò)內(nèi)核分析與開(kāi)發(fā)
- 新手學(xué)電腦從入門(mén)到精通(Windows 10+Office 2016版)
- Linux自動(dòng)化運(yùn)維:Shell與Ansible(微課版)
- 巧學(xué)活用Windows 7
- 嵌入式系統(tǒng)原理及開(kāi)發(fā)
- Windows Server 2012網(wǎng)絡(luò)操作系統(tǒng)項(xiàng)目教程(第4版)
- Hands-On UX Design for Developers
- Social Data Visualization with HTML5 and JavaScript
- Linux基礎(chǔ)使用與案例
- INSTANT Galleria Howto
- Hands-On GPU Programming with Python and CUDA
- Learning Joomla! 3 Extension Development(Third Edition)