JavaScript 101: Object Oriented JS


Reading the chapter related to OOP in Head First JS. Some basic rules:
Objects can be created as follows:

var myCar = {
 color: Red”,
 miles: 1321,
 model: Honda
};
It’s that simple.

Object properties can be accessed as follows:
myCar.color 
will yield “Red”.
No object can contain two or more properties with same names.


If you set a value of a property that doesn’t (yet) exist, it will be created. Like:
myCar.owner: Me”; 

will not throw an error, instead it will add the property owner to myCar variable.

Object properties can be deleted as follows:
delete myCar.miles; 
will simply drop the miles property from myCar object. delete returns a boolean value, which is true if it deleted the property or the property doesn’t exist, false if it encountered an error in deleting the property.

Objects don’t hold actual data, they hold references:
This is similar to Java. There are only a few primitive types: number, string, and boolean. A variable can contain this type of data directly. However, for objects and arrays, we have what is called as a reference type: it holds an address to the actual object. This is because we know beforehand the size of number, string and boolean variables. However the objects can contain 100’s of properties, so there’s no way to know their size beforehand. The object variables contain a reference to the actual object. However JS Engine abstracts the process of accessing the referenced object and makes it transparent to the user. Thus, normal and object variables can be accessed in a similar way.

Object are passed around as references:
Passing an object to a function isn’t same as passing a normal variable. JS is pass by value, or pass by copy, which means the variable will be copied and passed to the function. With objects, as we know that object variables hold references and not actual objects. Therefore, while passing to a function, the copy of the reference is passed, however the reference still points to the same object. Thus, a change made to the object in a function will change the original object.


var tito = {
  name: "Tito",
  age: 3
};
 
function growDog(dog) {
  dog.age++;
}
 
document.write(dog.name + " is " + tito.age + " years old.");
 
growDog(tito);
 
document.write(dog.name + " is " + tito.age + " years old.");

Will output: Tito is 3 years old.Tito is 4 years old.
 
This pointer is mandatory:
To access object properties from within the methods of the object, you must access it using a this pointer.
this is set to point to the current object when the method is called.

Ways of accessing a property:
Properties can be accessed in two ways:
object.propname 
Or
object[propname] 
These 2 forms are equivalent. The second form can accept any expression as long as it evaluates to a property name. Example:

object [“prop + name”] 
This cannot be done with the first method.

No comments:

Post a Comment