There are lots of ways of doing the same thing in JavaScript. I have however picked up some ways, and some ways I frankly don’t understand. Could anyone please help me clarify some things? (I first learnt OOP in PHP.)
So a class can be made like this:
var object = new class(constructparams) {
var private_members; // Can be accessed from within the code inside this definition only.
this.public_members; // Can be accessed from everywhere.
var private_functions = function() {}
this.public_functions = function() {}
}
object.prototype.semi_public_members = function() {
// Will be public, but can only access public members and methods.
// E. g. private_members; is not available here.
}
Is this all correct so far?
Then someone likes the self-executing anonymous function approach to create a namespace. What is the point of that, when you have this way above that does the same thing, provides a namespace?
And lastly you have the object literal notation that I don’t understand.
var object = { // Something strange in here }
What is going on in there? Is it JSON? How is it used, how can I use it. What are the benefits of using this way instead of using the method I described? Why would you prototype instead of making the class correctly the first time?
Explaining the behaviour of different things in a constructed object by example:
After executing the above code, you have a constructor that creates objects with both instance-specific and shared variables. Now let’s look at how they behave by creating two of instances and comparing them before and after some changes.
Here are the two logged statements together for easier viewing