I created a page on which there’s a red square that can be moved by a mouse. I would like to find out how I can reuse Javascript to have more than 1 square. In the following fiddle http://jsfiddle.net/sbel/utM5k/ I show that in HTML on top I include the CSS, the square is a div and the Javascript has the form (function(window) {…})(window);. How can I change the Javascript to be able to simply say here is the ID of a div, apply the moving functionality to it?
Share
Rather than wrapping your functionality (variables and functions) in an anonymous closure (which is a good idea to avoid cluttering the global namespace), instead wrap them in a “class” definition so you can create multiple instances of your new type.
For example (not tested):
This refactoring will take some time as you will be learning some new concepts (especially regarding the use of the “this” variable) but when complete you will be able to have any number of your movable objects as such:
This is the general way to achieve object oriented reusability in JavaScript (though the implementation specifics may vary greatly depending on your ideological preferences).