官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 泰兴市| 密云县| 澜沧| 六安市| 和顺县| 贡嘎县| 临泉县| 基隆市| 高州市| 牡丹江市| 丹凤县| 金寨县| 马鞍山市| 石城县| 偏关县| 大庆市| 社会| 奉新县| 昆明市| 宽城| 泾阳县| 扬中市| 旬邑县| 电白县| 南靖县| 榆社县| 鄯善县| 华宁县| 内黄县| 金华市| 北安市| 泸州市| 大厂| 阳城县| 洛扎县| 鸡西市| 宜章县| 丹阳市| 高淳县| 遂川县| 都兰县|