Object Oriented Javascript: © 2013, Cognizant Technology Solutions
Object Oriented Javascript: © 2013, Cognizant Technology Solutions
Primitive Types
Primitive types represent simple pieces of data that are stored as is, such as true and
25.
Primitive Types
// strings
var name = “Suman"; // null
var selection = "a"; var object = null;
// numbers // undefined
var count = 25; var flag = undefined;
var cost = 1.51; var ref; // assigned undefined automatically
// boolean
var found = true;
Primitive Types
When you assign a primitive value to a variable, the value is copied into that variable.
This means that if you set one variable equal to another, each variable gets its own
copy of the data. For example:
Because each variable containing a primitive value uses its own storage space, changes
to one variable are not reflected on the other. For example:
Primitive Types
console.log(color1); // "red"
console.log(color2); // "red“
color1 = "blue";
console.log(color1); // "blue"
console.log(color2); // "red"
This has been acknowledged as an error by TC39, the committee that designs and
maintains JavaScript.
Best way to test null is console.log(value === null); // true or false
Primitive Methods
Despite the fact that they’re primitive types, strings, numbers, and Booleans actually have
methods.
var name = “SUMAN";
var lowercaseName = name.toLowerCase(); // convert to lowercase
var firstLetter = name.charAt(0); // get first character
var middleOfName = name.substring(2, 5); // get characters 2-4
Despite the fact that they have methods, primitive values themselves are not objects.
JavaScript makes them look like objects to provide a consistent experience
Reference Types
Reference types represent objects in JavaScript and are the closest things to classes
Reference types do not store the object directly into the variable to which it is
assigned,
It holds a pointer (or reference) to the location in memory where the object exists.
This is the primary difference between objects and primitive values, as the primitive is
stored directly in the variable.
Reference Types
When you assign an object to a variable, you’re actually assigning a pointer.
That means if you assign one variable to another, each variable gets a copy of the
pointer, and both still reference the same object in memory. For example:
Dereferencing Objects
JavaScript is a garbage-collected language, so you don’t really need to worry about
memory allocations when you use reference types.
However, it’s best to dereference objects that you no longer need so that the garbage
collector can free up that memory.
The best way to do this is to set the object variable to null.
When there are no more references to an object in memory, the garbage collector
can use that memory for something else.
Literal Forms
A literal is syntax that allows you to define a reference value without explicitly creating
an object, using the new operator and the object’s constructor.
var book = {
name: "Object-Oriented JavaScript",
year: 2014
};
This example is equivalent to the previous one despite the syntactic differences. Both
examples are also logically equivalent to the following:
Function Literals
You almost always define functions using their literal form.
Creating functions is much easier and less error prone when you use the literal form.
function reflect(value) {
return value;
}
// is the same as
var reflect = new Function("value", "return value;");
Property Access
Properties are name/value pairs that are stored on an object.
Dot notation is the most common way to access properties in JavaScript (as in many
object-oriented languages), but you can also access properties on JavaScript objects by
using bracket notation with a string.
Other reference types are trickier to identify because, for all reference types other
than functions, typeof returns "object".
To identify reference types more easily, you can use JavaScript’s instanceof operator.
Identifying Arrays
Although instanceof can identify arrays, there is one exception that affects web
developers
When you pass an array from one frame to another, instanceof doesn’t work because
the array is actually an instance of Array from a different frame.
This method should return true when it receives a value that is a native array from any
context.
var items = [];
console.log(Array.isArray(items)); // true
The Array.isArray() method is supported in most environments, both in browsers and in
Node.js. This method isn’t supported in Internet Explorer 8 and earlier.
23 © 2013, Cognizant Technology Solutions
Primitive and Reference Types
Identifying Arrays
Although instanceof can identify arrays, there is one exception that affects web
developers
When you pass an array from one frame to another, instanceof doesn’t work because
the array is actually an instance of Array from a different frame.
This method should return true when it receives a value that is a native array from any
context.
var items = [];
console.log(Array.isArray(items)); // true
The Array.isArray() method is supported in most environments, both in browsers and in
Node.js. This method isn’t supported in Internet Explorer 8 and earlier.
24 © 2013, Cognizant Technology Solutions
Functions
what distinguishes it from any other object—is the presence of an internal property
named [[Call]].
ECMAScript defines multiple internal properties for objects in JavaScript, and these
internal properties are indicated by double-square-bracket notation.
The [[Call]] property is unique to functions and indicates that the object can be
executed.
The typeof operator is defined by ECMAScript to return "function" for any object with
a [[Call]] property.
The first is a function declaration, which begins with the function keyword and
includes the name of the function immediately following it
The second form is a function expression, which doesn’t require a name after function.
These functions are considered anonymous because the function object itself has no
name.
The function expression is almost identical to the function declaration except for the
missing name and the semicolon at the end.
Although these two forms are quite similar, they differ in a very important way.
Function declarations are hoisted to the top of the context (either the function in
which the declaration occurs or the global scope) when the code is executed.
That means you can actually define a function after it is used in code without
generating an error.
var result = add(5, 5);
function add(num1, num2)
{
return num1 + num2;
}
Function hoisting happens only for function declarations because the function name is
known ahead of time.
Function expressions, on the other hand, cannot be hoisted because the functions can
be referenced only through a variable.
Parameters
Another unique aspect of JavaScript functions is that you can pass any number of
parameters to any function without causing an error.
Overloading
Object Methods
You can add a method to an object in the same way that you would add a property.
var person = {
name: “Suman",
sayName: function() {
console.log(person.name);
}
};
person.sayName(); // outputs “Suman"
The sayName() method references person.name directly, which creates tight coupling
between the method and the object.
If you change the variable name, you also need to remember to change the reference
to that name in the method.
This sort of tight coupling makes it difficult to use the same function for different
objects.
Every scope in JavaScript has a this object that represents the calling object for the
function.
In the global scope, this represents the global object (window in web browsers).
When a function is called while attached to an object, the value of this is equal to that
object by default.
var person = {
name: “Suman",
sayName: function() {
console.log(this.name);
}
};
person.sayName(); // outputs “Suman"
Changing this
The ability to use and manipulate the this value of functions is key to good object-
oriented programming in JavaScript
Even though this is typically assigned automatically, you can change its value to achieve
different goals.
There are two function methods that allow you to change the value of this.
The call() Method
The first function method for manipulating this is call(), which executes the function
with a particular this value and with specific parameters.
The first parameter of call() is the value to which this should be equal when the
function is executed.
All subsequent parameters are the parameters that should be passed into the function
function sayNameForAll(label) {
console.log(label + ":" +
this.name); }
var person1 = {
name: “Suman“
var name = “Cognizant";
};
var person2 =
sayNameForAll.call(this, "global"); // outputs "global: Cognizant "
{
name: “Mishra“
sayNameForAll.call(person1, "person1"); // outputs "person1:Suman“
};
The apply() method works exactly the same as call() except that it accepts only two
parameters: the value for this and an array or array-like object of parameters to pass
to the function
function sayNameForAll(label) {
console.log(label + ":" +
this.name); } var name = “Cognizant";
var person1 = {
name: “Suman“ sayNameForAll.apply(this, ["global"]); // outputs "global: Cognizant "
};
var person2 = sayNameForAll.apply(person1, ["person1"]);// outputs "person1:Suman“
{
name: “Mishra“ sayNameForAll.apply(person2, ["person2"]); // outputs "person2:Mishra"
};