- The Node Craftsman Book
- Manuel Kiessling
- 403字
- 2021-07-02 23:36:52
Creating objects
Let's pe into code a bit, shall we? How could we set up our code in order to allow us to create our myCar object, ending up with an object that is a Car and can therefore honk and drive?
Well, in the most simple sense, we can create our object completely from scratch, or ex nihilo if you prefer the boaster expression.
It works like this:
var myCar = {}; myCar.honk = function() { console.log('honk honk'); }; myCar.drive = function() { console.log('vrooom...'); };
This gives us an object called myCar that is able to honk and drive:
myCar.honk(); // outputs "honk honk"
myCar.drive(); // outputs "vrooom..."
However, if we were to create 30 cars this way, we would end up defining the honk and drive behaviour of every single one, something we said we want to avoid.
In real life, if we made a living out of creating, say, pencils, and we don't want to create every pencil inpidually by hand, then we would consider building a pencil-making machine, and have this machine create the pencils for us.
After all, that's what we implicitly do in a class-based language like Java – by defining a class Car, we get the car-maker for free:
Car myCar = new Car();
will build the myCar object for us based on the Car blueprint. Using the new keyword does all the magic for us.
JavaScript, however, leaves the responsibility of building an object creator to us. Furthermore, it gives us a lot of freedom regarding the way we actually build our objects.
In the most simple case, we can write a function which creates plain objects that are exactly like our ex nihilo object, and that don't really share any behaviour – they just happen to roll out of the factory with the same behaviour copied onto every single one, if you want so.
Or, we can write a special kind of function that not only creates our objects, but also does some behind-the-scenes magic which links the created objects with their creator. This allows for a true sharing of behaviour: functions that are available on all created objects point to a single implementation. If this function implementation changes after objects have been created, which is possible in JavaScript, the behaviour of all objects sharing the function will change accordingly.
Let's examine all possible ways of creating objects in detail.
- Mastering vRealize Operations Manager(Second Edition)
- Instant Handlebars.js
- Haskell Financial Data Modeling and Predictive Analytics
- Java EE 8 Design Patterns and Best Practices
- 奔跑吧 Linux內核(入門篇)
- 新手學電腦從入門到精通(Windows 10+Office 2016版)
- 網絡操作系統管理與應用(第三版)
- Windows 7中文版從入門到精通(修訂版)
- VMware NSX Cookbook
- Windows 7應用入門與技巧
- 從實踐中學習Kali Linux無線網絡滲透測試
- INSTANT Galleria Howto
- Linux操作系統
- Ubuntu Linux操作系統實用教程
- Linux內核API完全參考手冊(第2版)