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

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.

主站蜘蛛池模板: 咸宁市| 平远县| 凌云县| 都昌县| 崇州市| 道孚县| 巴南区| 龙陵县| 澄城县| 清河县| 龙江县| 建阳市| 井冈山市| 河南省| 淳安县| 年辖:市辖区| 安庆市| 福建省| 神农架林区| 惠来县| 喀什市| 石景山区| 墨玉县| 南宁市| 通榆县| 萨嘎县| 永丰县| 循化| 武山县| 齐齐哈尔市| 安国市| 邹城市| 扎赉特旗| 长顺县| 紫云| 亚东县| 黑河市| 金昌市| 文水县| 岳阳县| 定边县|