Now to create an instance of this object, we use this (Note: I am using Prototype JS to run this code when the page has finished loading):
Put this div somewhere on the page:
You can also create multiple different DIVs and create new counter objects to instantiate them.
I admit it is a little weird, being a function inside of a function. The concepts are heavily tied in to the notion of “scopes” where you have to know which variables are global to the page (window) and which are local variables to the class. The outer anonymous function basically creates an instance of an inner function called “_class”, then it returns it, basically assigning a new object complete with its own variables and methods, to your desired variable instance.
Inside of the _class() function we have variables, created with the “var” keyword, which can be thought of as object properties.
It starts getting weird when you see “_self” being used in the “calcChange” method. Note that in other methods, we use the “this” keyword to refer to the object’s properties and methods. But in the “calcChange” method, you see “_self” in place of the “this” keyword. Why? If you look at the end of the init method you’ll see a setTimeout statement, which calls this.calcChange. Because of the way setTimeout works with scopes, when it is ready to fire, it doesn’t know anything about “this” (the object we want to work with). But it DOES know about “_self” — that is because we have assigned “this” to “_self” as a property of the class. When you write setTimeout, it knows about _self so it carries the variable over with it.
Therefore, if you want to act upon an object in a function called with setTimeout or setInterval, you have to make sure to set “var _self = this” before calling the setTimeout function. Then, use _self instead of this to refer to the object methods and properties.