object oriented java script
TRANSCRIPT
Object Oriented JavaScript
VIVEK.P.S
http://vivekcek.wordpress.com
Agenda
• Objects in JavaScript
• Functions: Declaration, Expression and Invocation
• this keyword
• Scopes and Closures
• Object oriented programming
Objects in JavaScript
Objects in JavaScript
• From one side, an object is an associative array (called hash in some languages).
• It stores key-value pairs
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
Literal syntax
It is also possible to create nested objects
Non-existing properties, undefined
• But if the property does not exist, then undefined is returned
Checking if a key exists
Iterating over keys-values
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
An Example
Properties and methods
• You can store anything in object. Not just simple values, but also functions.
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.
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.
A simple example
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.
An example with the method
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).
Functions: declarations, expressions and Invocation
The syntax
• function f(arg1, arg2, ...) {
... code ...
}
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
}
Local variables
• variables, defined by var. Such variables are called local and are only visible inside the function
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
Function Expression
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.
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.
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.
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
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.
Summary
this
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
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.
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
Third, in new
• When a new function is called, this is initialized as a new object
Fourth, explicit this
• A function can be called with explicit this value. This is done out by one of two methods: call or apply
Call
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')
Summary
Scopes and Closures
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.
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.
• 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)
• Second, the interpreter scans for var declarations and creates window properties. Assignments are not executed at this stage. All variables start as undefined.
• 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
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.
• Then the function code runs, eventually assignments are executed.A variable assignment internally means that the corresponding property of theLexicalEnvironment gets a new value.
Closures
• So variable is a property of the LexicalEnvironment object
• Here we discuss access to outer variables and nested functions
Access to outer variables
Nested functions• Functions can be nested one inside another,
forming a chain of LexicalEnvironments which can also be called a scope chain
Closures
• Nested function may continue to live after the outer function has finished:
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.
[[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.
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).
Object Oriented Programming
Prototypal inheritance
• In JavaScript, the inheritance is prototype-based. That means that there are no classes. Instead, an object inherits from another object
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
The prototype
• There is a good and crossbrowser way of setting __proto__. It requires the use of constructor functions.
hasOwnProperty
• All objects have hasOwnProperty method which allows to check if a property belongs to the object or its prototype.
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
OOP patterns
Module pattern
Revealing Module pattern
var self = this
var self = this