I’m a bit confused as to the purpose of constructor functions in javascript. I know that creating a constructor function through use of the new keyword also creates a new instance of a global object. Is that all one can do with them?
Also, the prototype of the new instance is the same as the global object, so why not just use the global object as many times as you need to instead of creating an instance? Can one add properties to a new instance?
Also, what points about constructor functions am I missing? Any help understanding this would be much appreciated.
That’s not right. Invoking a function with
newcreate a new object, but it’s not global. It’s an instance of that function, and will have that function referenced as its.constructor.Theprototypeis simply the object that all the instances of the constructor function point to. It lets all your instances reference a common set of properties.The
prototypeis simply the object to which all the instances created by the constructor function contain an implicit pointer. It lets all your instances reference a common set of properties.Yes, they will be added to the object that was created from the constructor and not to its prototype.
EDIT: Here’s an example that is a very simple DOM wrapper:
http://jsfiddle.net/CEVwa/
The constructor places a separate
countproperty initialized to0on each instance that is created from it.If you pass the constructor a String, it will automatically call the
fetchByIdthat is on theprototype. Otherwise you can callfetchById()directly after the new instance is returned.Upon a successful
getElementById, thefetchByIdstores the element found on theelementproperty of that instance and calls thesetupmethod, which storesclickevent listener on the.listenerproperty of the element, and adds uses it to add aclickevent listener to the element.The listener just increments the counter for that instance, and appends the new count to the element.
Once the
countreaches10, thetear_downmethod is called to remove the listener.