Thursday, 15 September 2011

javascript - returning a variable as a constructor function . -


Hey guys, I'm new to javascript and I was advised to read the book, I was reading the factory design pattern The following difficulty is just a look at the script below:

  // types.js - constructor car used to define the car's new car / a constructor car behind the constructor (option) / Something missed this Doors = option 4; This.state = options.state || "Brand new"; This.color = options.color || "silver"; } // A constructor to define a new truck pane truck (option) {this.state = options.state || "Used"; this. WheelSize = options.wheelSize || "Vishal"; This.color = options.color || "Blue"; } // FactoryExample.js // Define a skeletal vehicle factory function VehicleFactory () {} // Define prototypes and utilities for this factory // Our default vehicle class car vehicle is Factory.prototype.vehicleClass = Car; // Our VehicleFactory.prototype.createVehicle = Function (Option) {Switch (options.vehicleType) {Case "Car": This.vehicleClass = Car; New Vehicle Example Vehicle; break; Case "Truck": this.vehicleClass = Truck; break; // Default for VehicleFactory.prototype.vhicleClass (car); New.rehicleClass (option); }; // Make an example of our factory, which makes cars car Factory = new vehicle factory (); Var car = carfactinator.quiteval (vehicle type: "car", color: "yellow", doors: 6}); // Test our car to confirm the use of vehicle class / prototype car // output: true console.log (car example car); // Output: color "yellow" car object, doors: 6 "brand new" in the state console.log (car);  

This is an example I found for factory design patterns, now my problem is understanding the following line:

That vehicle class class is used as a variable Defined:

  VehicleFactory.prototype.vehicleClass = Car;  

I do not understand that it is being returned as a constructor function:

  return this new one. HhicleClass (option);  

It's my only problem and is going on repeatedly code, yet I do not understand

I would be happy if someone told me this

thanks

Alexander

here It's not a function that's returned (you're right that does not make sense). Is a new object returned (see the new key word)

When you want to replace a new object type truck with you

However in this specific case, the type of vehicle you want It is defined by the user. Then the this.vehicleClass refers to the value defined in the switch above the return. In other words, if car ( car ) is selected, then vehicle class to car (resp. Truck ). trucks ).

Thus the constructor will be defined in either the car or truck manufacturer, the first line of code.

I hope this is more clear now.


No comments:

Post a Comment