Make delicious recipes!

Creating Objects: User-defined objects can be defined in two ways:

  1. By directly adding fields and methods. Example

    	var personObj; = "John";
    	personObj.age = 21; = someEatFunction;
  2. By having a function which creates objects. Example:

    	function personObj (name, age, eatFunction) { = name;
    		this.age = age; = eatFunction;
    	var person1 = new personObj ("John", 21, someEatFunction);

When to use var

Consider the following 2 statements:

var foo = "hi";

bar = "hi";

Both the above statements create a variable, if they are executed at the global level.

But if the context is not global, i.e. we are inside some function, then the
first statement creates a local variable while the second statement first
looks up the enclosing scopes to find a variable name bar. If bar is found,
then it assigns the value to that variable, else it creates a new
variable bar at the global scope.

Private members in an object

All the members of an object are public in javascript.

Only exception are the variables declared using ‘var’ in the constructor. These variables are visible only in the constructor, not visible even to other public members of the class.

So truly speaking, these variables/methods are not even private, they are like local variables of the constructor.

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal