0% found this document useful (0 votes)
10K views

Object Oriented Javascript: © 2013, Cognizant Technology Solutions

Uploaded by

siddharth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10K views

Object Oriented Javascript: © 2013, Cognizant Technology Solutions

Uploaded by

siddharth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Object Oriented JavaScript

1 © 2013, Cognizant Technology Solutions


What will be covered?

 Primitive and Reference Types


 Functions
 Understanding Objects
 Constructors and Prototypes
 Inheritance
 Object Patterns

2 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

 What Are Types?


 Primitive Types
 Reference Types
 Instantiating Built-in Types
 Property Access
 Identifying Reference Types
 Identifying Arrays

3 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

 Most developers learn object-oriented programming by working with class-based


languages such as Java or C#.
 JavaScript has no formal support for classes.
 JavaScript also lacks class groupings such as packages
 Programming in JavaScript is like starting with a blank slate
 You can organize things any way you want.
 JavaScript makes objects the central part of the language.
 Almost all data in JavaScript is either an object or accessed through objects.
 Even functions are represented as objects in JavaScript, which makes them first-class
functions
 Working with and understanding objects is key to understanding JavaScript as a
whole.

4 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

 JavaScript uses two kinds of types: primitive and reference.


 Primitive types are stored as simple data types
 Reference types are stored as objects, which are really just references to locations in
memory.
 The tricky thing is that JavaScript lets you treat primitive types like reference types in
order to make the language more consistent for the developer.

5 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Primitive Types

 Primitive types represent simple pieces of data that are stored as is, such as true and
25.

6 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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;

7 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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:

var color1 = "red";


var color2 = color1;

Because each variable containing a primitive value uses its own storage space, changes
to one variable are not reflected on the other. For example:

8 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Primitive Types

var color1 = "red";


var color2 = color1;

console.log(color1); // "red"
console.log(color2); // "red“

color1 = "blue";

console.log(color1); // "blue"
console.log(color2); // "red"

9 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Identifying Primitive Types


The best way to identify primitive types is with the typeof operator, which works on any
variable and returns a string indicating the type of data.

console.log(typeof “Suman"); // "string”


console.log(typeof 10); // "number"
console.log(typeof 5.1); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined“
console.log(typeof null); // "object"

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

10 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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

var count = 10;


var fixedCount = count.toFixed(2); // convert to "10.00"
var hexCount = count.toString(16); // convert to "a" var flag = true;
var stringFlag = flag.toString(); // convert to "true"

Despite the fact that they have methods, primitive values themselves are not objects.
JavaScript makes them look like objects to provide a consistent experience

11 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Reference Types
 Reference types represent objects in JavaScript and are the closest things to classes

 An object is an unordered list of properties consisting of a name (always a string) and a


value.
 When the value of a property is a function, it is called a method.

var object = new Object();

 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.

12 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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:

var object1 = new Object();


var object2 = object1;

13 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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.

var object1 = new Object();


// do something
object1 = null; // dereference

 When there are no more references to an object in memory, the garbage collector
can use that memory for something else.

14 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Adding or Removing Properties


 Another interesting aspect of objects in JavaScript is that you can add and remove
properties at any time. For example:

var object1 = new Object();


var object2 = object1;
object1.myCustomProperty = "Awesome!";
console.log(object2.myCustomProperty); // "Awesome!"

15 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Instantiating Built-in Types


 The Object type is just one of a handful of built-in reference types that JavaScript
provides

 The built-in types are:

16 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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:

var book = new Object();


book.name = "The Principles of Object-Oriented JavaScript";
book.year = 2014;

17 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Function Literals
 You almost always define functions using their literal form.

 Using the Function constructor is typically discouraged given the challenges of


maintaining, reading, and debugging a string of code rather than actual code

 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;");

18 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

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.

var array = [];


array.push(12345);

var array = [];


array["push"](12345);

var array = [];


var method = "push";
array[method](12345);

19 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Identifying Reference Types


 A function is the easiest reference type to identify because when you use the typeof
operator on a function, the operator should return "function":
function reflect(value) {
return value;
}
console.log(typeof reflect); // "function"

 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.

20 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Identifying Reference Types

var items = [];


var object = {};
function reflect(value) {
return value;
}
console.log(items instanceof Array); // true
console.log(object instanceof Object); // true
console.log(reflect instanceof Function); // true

21 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are Types?

Identifying Reference Types


var items = [];
var object = {};
function reflect(value)
{
return value;
}
console.log(items instanceof Array); // true
console.log(items instanceof Object); // true
console.log(object instanceof Object); // true
console.log(object instanceof Array); // false
console.log(reflect instanceof Function); // true
console.log(reflect instanceof Object); // true

22 © 2013, Cognizant Technology Solutions


Primitive and Reference Types

What Are 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.

 To solve this problem, ECMAScript 5 introduced Array.isArray(), which definitively


identifies the value as an instance of Array regardless of the value’s origin.

 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

What Are 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.

 To solve this problem, ECMAScript 5 introduced Array.isArray(), which definitively


identifies the value as an instance of Array regardless of the value’s origin.

 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

 Declarations vs. Expressions


 Parameters
 Overloading
 Object Methods

25 © 2013, Cognizant Technology Solutions


Functions

 As discussed in previous slides, functions are actually objects in JavaScript.

 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.

26 © 2013, Cognizant Technology Solutions


Functions

Declarations vs. Expressions

 There are actually two literal forms of functions.

 The first is a function declaration, which begins with the function keyword and
includes the name of the function immediately following it

function add(num1, num2)


{
return num1 + num2;
}

 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.

27 © 2013, Cognizant Technology Solutions


Functions

Declarations vs. Expressions

 function expressions are typically referenced via a variable or property, as in this


expression
var add = function(num1, num2)
{
return num1 + num2;
};

 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.

28 © 2013, Cognizant Technology Solutions


Functions

Declarations vs. Expressions

 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.

29 © 2013, Cognizant Technology Solutions


Functions

Parameters

 Another unique aspect of JavaScript functions is that you can pass any number of
parameters to any function without causing an error.

 Parameters are actually stored as an array-like structure called arguments.

 The arguments object is automatically available inside any function.

30 © 2013, Cognizant Technology Solutions


Functions

Overloading

 function overloading, is the ability of a single function to have multiple signatures.

31 © 2013, Cognizant Technology Solutions


Functions

Object Methods

 When a property value is actually a function, the property is considered a method.

 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"

32 © 2013, Cognizant Technology Solutions


Functions

The this Object

 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.

33 © 2013, Cognizant Technology Solutions


Functions

The this Object

var person = {
name: “Suman",
sayName: function() {
console.log(this.name);
}
};
person.sayName(); // outputs “Suman"

 sayName() references this instead of person

34 © 2013, Cognizant Technology Solutions


Functions

The this Object

function sayNameForAll() { var name = “Cognizant";


console.log(this.name);
} person1.sayName(); // outputs “Suman"
var person1 = { person2.sayName(); // outputs “Mishra"
name: “Suman",
sayName: sayNameForAll sayNameForAll(); // outputs “Cognizant"
};
var person2 =
{
name: “Mishra",
sayName: sayNameForAll
};

35 © 2013, Cognizant Technology Solutions


Functions

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 apply() Method

36 © 2013, Cognizant Technology Solutions


Functions

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

37 © 2013, Cognizant Technology Solutions


Functions

The call() Method

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“
};

sayNameForAll.call(person2, "person2"); // outputs "person2:Mishra"

38 © 2013, Cognizant Technology Solutions


Functions

The apply() Method

 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"
};

39 © 2013, Cognizant Technology Solutions


Thank You

40 © 2013, Cognizant Technology Solutions

You might also like