I am using Lightbox2
https://github.com/lokesh/lightbox2/blob/master/js/lightbox.js
And I don’t understand why all the inner members of Lightbox are prototyped (Lightbox.prototype.init) and not simply members (Lightbox.init)?
If they are specific to each instance of lightbox wouldn’t it be easier to use this.init?
Confused? Don’t be…
Think of it this way:
Lightbox is your class definition, but it’s not yet an instance.
Whatever you put directly on the class is like a static member:
Whatever you put on its prototype is a shared instance member:
When you create an instance of a class, all instance members are accessible throught
thiskeyword, but static ones through class definition:Does this clear you understanding of prototype members?
Lightbox code then
The code that you’ve been looking at means this:
But some parts of this code are a bit confusing i.e.
LightboxOptionsclass is contained within a function closure even though it doesn’t define any private data, so the outer immediately executing function could be omitted in this example while having identical results:It would of course be possible to define those functions in a constructor using
thisbut then they wouldn’t be shared between instances hence every object instance would define the same function hence consuming more resources. So this is not the same although from the execution point it does look the same:is slightly different than:
The later consumes more resources while function is defined for every object instance.
…and a bit more to completely clear this thing
Suppose we have this class definition:
What happens here if we call these lines of code
What do you think the output would be? You should get at least a little confused what happens after
delete? Which method will get deleted? Per instance? Shared? Both? Well as it should be per instance method gets deleted on object instancea, that’s why afterwards it reports that the shared method has been called. But only ona.bstill has its own per instance method.So without any further ado, output looks like this:
What about
prototypepropertiesThese are different. When you create an object instance all those properties get copied to every object and are not shared. So whatever you do on them within the realm of a particular object will not get reflected to others.
If you’d then delete such property on a particular object it would still be available with its initial value as it was when object got instantiated.