- 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.