In JavaScript I see a few different ways, certain tasks can be performed within an object for example, the object Egg I have below.
Can anyone tell me the difference between each one, why I would use one and not the other etc
var Egg = function(){
//Properties
var shell = "cracked" // private property
this.shell = "cracked" // public property
shell: "cracked" // what is this??
//functions
function cook(){
//standard function
}
cook: function(){
//what kind of function is this?
}
//not sure what this is
details: {
//What is this? an array :S it holds 2 elements?
cost: 1.23,
make: 'Happy Egg';
}
}
Sure, Ben.
This sort of gets to the bottom of the dynamism of JavaScript.
First, we’ll look at basics — if you’re coming from a place where you understand class-based languages, like, say, Java or C++/C#, the one that is going to make the most sense is the constructor pattern which was included very early on:
That’s fine, but sometimes there are easier ways of getting around things.
Sometimes you really don’t need a class.
What if you just wanted to use one egg, ever, because that’s all your recipe called for?
That’s great, but there’s still a lot of repetition there.
Both of the two “myEgg” objects are exactly the same.
The problem here is that EVERY property and EVERY method of myEgg is 100% public to anybody.
The solution to that is immediately-invoking functions:
Hope that’s a decent start.