object oriented java script

74
Object Oriented JavaScript VIVEK.P.S http://vivekcek.wordpress.com

Upload: vivek-p-s

Post on 15-Jul-2015

110 views

Category:

Software


3 download

TRANSCRIPT

Page 1: Object oriented java script

Object Oriented JavaScript

VIVEK.P.S

http://vivekcek.wordpress.com

Page 2: Object oriented java script

Agenda

• Objects in JavaScript

• Functions: Declaration, Expression and Invocation

• this keyword

• Scopes and Closures

• Object oriented programming

Page 3: Object oriented java script

Objects in JavaScript

Page 4: Object oriented java script

Objects in JavaScript

• From one side, an object is an associative array (called hash in some languages).

• It stores key-value pairs

Page 5: Object oriented java script

Creating objects

• An empty object (you may also read as empty associative array) is created with one of two syntaxes:

• 1. o = new Object()

• 2. o = { } // the same

Page 6: Object oriented java script
Page 7: Object oriented java script

Literal syntax

Page 8: Object oriented java script

It is also possible to create nested objects

Page 9: Object oriented java script

Non-existing properties, undefined

• But if the property does not exist, then undefined is returned

Page 10: Object oriented java script

Checking if a key exists

Page 11: Object oriented java script

Iterating over keys-values

Page 12: Object oriented java script

Object variables are references

• A variable which is assigned to object actually keeps reference to it. That is, a variable stores kind-of pointer to real data.

• The variable is a reference, not a value

Page 13: Object oriented java script

An Example

Page 14: Object oriented java script

Properties and methods

• You can store anything in object. Not just simple values, but also functions.

Page 15: Object oriented java script

Calling methods

• Note the this keyword inside askName and sayHi. When a function is called from the object, this becomes a reference to this object.

Page 16: Object oriented java script

The constructor function, “new”

• An object can be created, using

obj = { ..} syntax.

• Another way of creating an object in JavaScript is to construct it by calling a function with new directive.

Page 17: Object oriented java script

A simple example

Page 18: Object oriented java script

A simple example

• A function takes the following steps:

• Create this = {}.

• The function then runs and may change this, add properties, methods etc.

• The resulting this is returned.

• So, the function constructs an object by modifying this.

Page 19: Object oriented java script

An example with the method

Page 20: Object oriented java script

Summary

• Objects are associative arrays with additional features.– Assign keys with obj[key] = value or obj.name = value– Remove keys with delete obj.name– Iterate over keys with for(key in obj), remember iteration order for

string keys is always in definition order, for numeric keys it may change.

• Properties, which are functions, can be called as obj.method(). They can refer to the object as this.

• Properties can be assigned and removed any time.• A function can create new objects when run in constructor mode

as new Func(params).It takes this, which is initially an empty object, and assigns properties to it. The result is returned (unless the function has explicit return anotherObject call).

Page 21: Object oriented java script

Functions: declarations, expressions and Invocation

Page 22: Object oriented java script

The syntax

• function f(arg1, arg2, ...) {

... code ...

}

Page 23: Object oriented java script

Returning a value

• use return statement

If a function does not return anything, it’s result is considered to be a special value, undefined

• function getNothing() {// no return

}

Page 24: Object oriented java script

Local variables

• variables, defined by var. Such variables are called local and are only visible inside the function

Page 25: Object oriented java script

Function Declaration

• Function Declarations are parsed at pre-execution stage, when the browser prepares to execute the code.

• why the function declared this way can be called both after and before the definition

Page 26: Object oriented java script

Function Expression

Page 27: Object oriented java script

Function Expression

• Function Expressions are created when the execution flow reaches them. As a consequence, Function Expressions can be used only after they are executed.

Page 28: Object oriented java script

Function is a value

• A function in JavaScript is a regular value. We could even output it

• a function can be assigned, passed as a parameter for another function and so on.

Page 29: Object oriented java script

Running at place

• Running in place is mostly used when we want to do the job involving local variables. We don’t want our local variables to become global, so wrap the code into a function.

• After the execution, the global namespace is still clean. That’s a good practice.

Page 30: Object oriented java script

Named function expressions

• The syntax is called named function expression

• the name is visible inside the function only

• NFEs exist to allow recursive calls from anonymous functions

Page 31: Object oriented java script

Summary

• Functions in JavaScript are regular values. They can be assigned, passed around and called when needed.

• A function which returns nothing actually returns special value: undefined.

• Use verbs to name functions. Short names are allowable in two edge cases: a name is used in the nearest code only, or it is extremely widely used.

Page 32: Object oriented java script

Summary

Page 33: Object oriented java script

this

Page 34: Object oriented java script

Introduction

• The value of this is dynamic in JavaScript

• It is determined when function is called, not when it is declared

• Any function may use this. It doesn’t matter if the function is assigned to the object or not

• The real value of this is evaluated in the call time anyway, and there are 4 possible cases

Page 35: Object oriented java script

First, when called as a method

• If a function is called from the object (either dot or square bracket will do), this refers to this object.

• In the example above, func is initially apart from the object. But when called john.sayHi() sets this to the object before dot: john.

Page 36: Object oriented java script

Second, when called as a function

• If a function uses this, then it is meant to be called as a method. A simple func() call is usually a bug

Page 37: Object oriented java script

Third, in new

• When a new function is called, this is initialized as a new object

Page 38: Object oriented java script

Fourth, explicit this

• A function can be called with explicit this value. This is done out by one of two methods: call or apply

Page 39: Object oriented java script

Call

Page 40: Object oriented java script

apply

• The func.apply is same as func.call, but it accepts an array of arguments instead of a list

• The following two lines are same:

• func.call(john, 'firstName', 'surname')

Page 41: Object oriented java script

Summary

Page 42: Object oriented java script

Scopes and Closures

Page 43: Object oriented java script

Initialization of functions and variables

• In JavaScript, all local variables and functions are properties of the special internal object, called LexicalEnvironment

• The top-level LexicalEnvironment in browser is window. It is also called a global object.

Page 44: Object oriented java script

Instantiation of top-level variables

• When the script is going to be executed, there is a pre-processing stage called variables instantiation.

• The top-level LexicalEnvironment in browser is window. It is also called a global object.

Page 45: Object oriented java script

• the browser finds function f, creates the function and stores it as window.f

• Function Declarations are initialized before the code is executed.

• As a side effect, f can be called before it is declared (Hoisting)

Page 46: Object oriented java script

• Second, the interpreter scans for var declarations and creates window properties. Assignments are not executed at this stage. All variables start as undefined.

Page 47: Object oriented java script

• FunctionDeclarations become ready-to-use functions. That allows to call a function before it’s declaration.

• Variables start as undefined.

• All assignments happen later, when the execution reaches them

Page 48: Object oriented java script

Function variables

• When the interpreter is preparing to start function code execution, before the first line is run, an empty LexicalEnvironment is created and populated with arguments, local variables and nested functions.

Page 49: Object oriented java script

• Then the function code runs, eventually assignments are executed.A variable assignment internally means that the corresponding property of theLexicalEnvironment gets a new value.

Page 50: Object oriented java script

Closures

• So variable is a property of the LexicalEnvironment object

• Here we discuss access to outer variables and nested functions

Page 51: Object oriented java script

Access to outer variables

Page 52: Object oriented java script

Nested functions• Functions can be nested one inside another,

forming a chain of LexicalEnvironments which can also be called a scope chain

Page 53: Object oriented java script

Closures

• Nested function may continue to live after the outer function has finished:

Page 54: Object oriented java script
Page 55: Object oriented java script

Closure

• The inner function keeps a reference to the outer LexicalEnvironment.

• The inner function may access variables from it any time even if the outer function is finished.

• The browser keeps the LexicalEnvironment and all it’s properties(variables) in memory until there is an inner function which references it.

• This is called a closure.

Page 56: Object oriented java script

[[Scope]] for new Function• There is an exception to general scope binding

rule. When you create a function using new Function, it’s[[Scope]] points to window, not to current LexicalEnvironment.

Page 57: Object oriented java script

Summary

• How variables are handled in JavaScript.

• How scopes work.

• What is a closure and how to use it.

• Possible pitfalls and subtles in working with closures.

• In JavaScript, a variable can be declared after it has been used (Hoisting).

• In other words; a variable can be used before it has been declared (Hoisting).

Page 58: Object oriented java script

Object Oriented Programming

Page 59: Object oriented java script

Prototypal inheritance

• In JavaScript, the inheritance is prototype-based. That means that there are no classes. Instead, an object inherits from another object

Page 60: Object oriented java script
Page 61: Object oriented java script
Page 62: Object oriented java script
Page 63: Object oriented java script
Page 64: Object oriented java script

Object.create, Object.getPrototypeOf

• The __proto__ is a non-standard property, provided by Firefox/Chrome. In other browsers the property still exists internally, but it is hidden

Page 65: Object oriented java script
Page 66: Object oriented java script

The prototype

• There is a good and crossbrowser way of setting __proto__. It requires the use of constructor functions.

Page 67: Object oriented java script
Page 68: Object oriented java script

hasOwnProperty

• All objects have hasOwnProperty method which allows to check if a property belongs to the object or its prototype.

Page 69: Object oriented java script

Summary

• The inheritance is implemented through a special property __proto__ (named [[Prototype]] in the specification).

• When a property is accessed, and the interpreter can’t find it in the object, it follows the __proto__link and searches it there.

• The value of this for function properties is set to the object, not its prototype.

• Assignment obj.prop = val and deletion delete obj.prop

Page 70: Object oriented java script

OOP patterns

Page 71: Object oriented java script

Module pattern

Page 72: Object oriented java script

Revealing Module pattern

Page 73: Object oriented java script

var self = this

Page 74: Object oriented java script

var self = this