Make delicious recipes!


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

  1. By directly adding fields and methods. Example

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

    
    	function personObj (name, age, eatFunction) {
    		this.name = name;
    		this.age = age;
    		this.eat = 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:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal