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

Using a simple function to create plain objects

In our first example, we created a plain myCar object out of thin air  we can simply wrap the creation code into a function, which gives us a very basic object creator:

var makeCar = function() {
  var newCar = {}; 
  newCar.honk = function() {
    console.log('honk honk');
  };
};

For the sake of brevity, the drive function has been omitted.

We can then use this function to mass-produce cars:

var makeCar = function() { 
  var newCar = {} 
  newCar.honk = function() {
    console.log('honk honk'); 
  }; 
  return newCar; 
};

myCar1 = makeCar();
myCar2 = makeCar();
myCar3 = makeCar();

One downside of this approach is efficiency: for every myCar object that is created, a new honk function is created and attached  creating 1,000 objects means that the JavaScript interpreter has to allocate memory for 1,000 functions, although they all implement the same behaviour. This results in an unnecessarily high memory footprint of the application.

Secondly, this approach deprives us of some interesting opportunities. These myCar objects don't share anything  they were built by the same creator function, but are completely independent from each other.

It's really like with real cars from a real car factory: They all look the same, but once they leave the assembly line, they are totally independent. If the manufacturer should decide that pushing the horn on already produced cars should result in a different type of honk, all cars would have to be returned to the factory and modified.

In the virtual universe of JavaScript, we are not bound to such limits. By creating objects in a more sophisticated way, we are able to magically change the behaviour of all created objects at once.

主站蜘蛛池模板: 尼勒克县| 武清区| 永福县| 屯昌县| 赣榆县| 自治县| 河源市| 甘泉县| 邹城市| 庆云县| 宁波市| 玛沁县| 南城县| 望谟县| 牙克石市| 隆德县| 广灵县| 贵定县| 洪雅县| 甘谷县| 巴里| 临沂市| 同仁县| 措美县| 吴堡县| 巴彦县| 商南县| 海南省| 小金县| 四平市| 喀什市| 台州市| 陆丰市| 西平县| 即墨市| 浦城县| 施甸县| 玉屏| 明光市| 武义县| 东方市|