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

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.

主站蜘蛛池模板: 玛多县| 蚌埠市| 营山县| 玛纳斯县| 交城县| 武陟县| 万全县| 来安县| 吉安县| 南昌市| 喀什市| 邹城市| 宜君县| 英德市| 常熟市| 安阳县| 师宗县| 澄迈县| 图片| 平遥县| 越西县| 安康市| 鄱阳县| 明星| 兴海县| 邢台市| 望谟县| 锦州市| 和林格尔县| 龙胜| 建湖县| 黔江区| 嵊泗县| 平阴县| 准格尔旗| 普安县| 祁阳县| 龙南县| 福泉市| 珠海市| 澜沧|