advanced javascript
DESCRIPTION
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.TRANSCRIPT
![Page 1: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/1.jpg)
1
Advanced JavaScriptAdvanced JavaScript
Alex Cheng (CHENG Fu)
![Page 2: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/2.jpg)
2
About Me
• Front-end engineer• Web 2.0 enthusiast
• Located in Beijing, China
• My personal website (Chinese)– http://www.cheng-fu.com
• Email : [email protected]• Twitter : alexcheng1982
![Page 3: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/3.jpg)
3
Those NOT Included
• Document Object Model
• Browser Object Model
• JavaScript Libraries
• Built-in Objects– Array, Date, RegExp
![Page 4: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/4.jpg)
4
How the value of obj.myVar get resolved?
![Page 5: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/5.jpg)
5
Prototype Chain
• Each object has a special property called prototype.
• Value of this property is an object reference points to another object.– The second object can has its prototype point
s to another object.
• A prototype chain is formed in this way.• An identifier is resolved by searching upwa
rds in the prototype chain.
![Page 6: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/6.jpg)
6
Search for an Identifier
Find the propertyin current object
Return the value
Value of current object's prototype is not null
Return undefined
Set current object tothe value of its prototype
Y
Y
N
N
The search process
![Page 7: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/7.jpg)
7
More about Prototype Chain
• Long prototype chain can harm performance.– Use local variables for long property access e
xpressions.• Be ware of accidental property hiding caus
ed by prototype chain.• An object's properties can be enumerated
using for..in expression. – Properties from other objects in prototype chai
n are also included.• Use hasOwnProperty to filter out these properties.
![Page 8: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/8.jpg)
8
What can JavaScript do for OO enthusiasts?
![Page 9: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/9.jpg)
9
• No Classes in JavaScript.• Just Objects.
• But you can see this kind of code in JavaScript.
It looks like we have classes in JavaScript, just like Java.
![Page 10: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/10.jpg)
10
Prototype-based Inheritance
• We can use prototype chain and new operator to implement pesudo-inheritance.– The formal name is prototype-based inherit
ance.
• It's not the classical inheritance we can do in Java.– State is also inherited in JavaScript.
![Page 11: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/11.jpg)
11
Inheritance in JavaScript
• The main reason we need inheritance is to reuse code.– Instances of sub-classes can use attributes a
nd methods from super-classes.
• Inheritance in JavaScript is easy.– Just make sure the super-class appears in the
sub-class's prototype chain.– Instances of sub-class can search upwards its
prototype chain to find attributes and methods in super-class and use them.
Note: The underlined words are for understanding the concept only.
![Page 12: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/12.jpg)
12
• Use new operator to create a new object from another object. – The object can be used to create another object is cal
led a constructor.– Every object created by a constructor has an implicit r
eference (called the object’s prototype) to the value of its constructor’s prototype property.
new Operator
user object has a references to its constructor User's prototype. So the property sa
yHi can be found.
![Page 13: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/13.jpg)
13
Classical Inheritance Sample
• Person is the super-class.• Student is the sub-class.• Student class inherites getNa
me function from Person and declares its own function getEmail.
![Page 14: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/14.jpg)
14
aStudent Student
prototype object
PersonaPerson
prototypeobject
getEmail getName
new new
Student.prototype = new Person();
Search path of aStudent.getName
Student's prototype object -> Person's prototype objectConstructor's prototype
Constructor
Objects created by new operator
Implicit references to constructor's prototype
Note: aPerson doesn't exist in the code.
Properties
![Page 15: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/15.jpg)
15
• Be careful when using objects from prototype chain– All the objects created from the same constructor sha
re the same prototype object.• This is error prone for object references.
Shared Objects
emails is shared by user1 and user2.
The correct way
![Page 16: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/16.jpg)
16
Composition
• Another way to enable reuse is to use object composition.– Each object provides a small set of functions
and maintain its internal states.– Favor immutable objects and functional style.
• This kind of objects can be composed or mixed into other objects.
• Use a factory to encapsulate the composition and produce well-behaved objects.
![Page 17: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/17.jpg)
17
Duck Typing
• Inheritance is used to express is-a relationship.• JavaScript provides instanceof operator to check
whether an object is constructed by another object.– But the better way is not to check the type.
• Categorize objects by their behaviors, not their inheritance hierarchy.– "when I see a bird that walks like a duck and swims lik
e a duck and quacks like a duck, I call that bird a duck." http://en.wikipedia.org/wiki/Duck_typing
![Page 18: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/18.jpg)
18
Duck Typing cont.
• Duck typing is very natural in JavaScript.
• An object's behavior can be determined by the functions it has, including those from its prototype chain.
• If an object provides all the functions that a type requires, we can say this object is an instance of that type.
![Page 19: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/19.jpg)
19
A Duck Typing Sample
• Function sayHiForMe only requires the object any contains a function sayHi.
• It doesn't check the type of object any.
![Page 20: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/20.jpg)
20
What happends when I invoke myFunc()?
![Page 21: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/21.jpg)
21
Execution Context
• All JavaScript code is executed in certain execution context (EC).
• When a function is invoked in current EC, the execution flow enters a new EC.
• When the function is returned, the execution flow returns to the caller EC.
• A EC stack is formed in this way.
![Page 22: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/22.jpg)
22
Scope Chain
• Each execution context is associated with a scope chain.
• The scope chain is used to resolving identifiers at runtime.– The scope chain is a chain of objects.– Identifier resolving starts from the first object a
nd iterate over the whole chain until a property is found or meets the last object.
– The prototype chain of an object in scope chain is used when searching for a property.
![Page 23: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/23.jpg)
23
EB CA D
B1 C1
A2
A1 D1 E1
C2
Scope Chain
Prototype Chain
Search path: A -> A1 -> A2 -> B -> B1 -> C -> C1 -> C2 -> D -> D1 -> E -> E1
![Page 24: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/24.jpg)
24
When Entering an EC
• Create the Activation object– It has the property arguments which contains actual parameters.
• Create the scope chain– Create a scope chain
• For function declaration and expression, the scope chain is the same as that associated with current EC.
• For Function constructor, the scope chain always contains global object only.
– Put Activation object to the head of the chain.
• Initialize variables– Formal parameters, local variables and inner functions are intiali
zed as properties of the Activation object
Note: All these steps are done BEFORE the function body is executed.
![Page 25: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/25.jpg)
25
A Quiz
This quiz is based on http://ejohn.org/apps/learn/#8
Function getSOSNumber is initialized when entering the EC. So it can be invoked even its body appears after
a return statement.
getSOSNumber is a local variable which is undefined when entering the EC. It's initialized when executi
ng the assign operator.
Function declarationv.s.
Function expression
![Page 26: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/26.jpg)
26
Scope Chain Augmentation
• Scope chain can be augmented during function execution using with statement and catch clause.– The object declared will be put to the head of
the scope chain.– It affects the behavior of identifier resolving.
• Properties in the object will be searched first.
• Scope chain will be restored after existing the code block.
![Page 27: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/27.jpg)
27
A with Sample
objGlobalObject
name
Scope chain
• obj is put to the head of scope chain.• name property in obj is found first.
![Page 28: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/28.jpg)
28
Why can you use alert() everywhere?
![Page 29: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/29.jpg)
29
Global Object
• Although usage of global object is generally considered as a bad practice, it exists in JavaScript and plays an important role in identifier resolving.
• Global object is provided by host environment.– In browser, it's the window object.
• The global object contains many properties that you use in everyday coding.– NaN, undefined, Math, Array, Date, parseInt, parseFlo
at, etc.
![Page 30: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/30.jpg)
30
Global Object cont.
• Global object is the last object in a scope chain.– It's the last chance an identifier got resolved.
• It has performance penalty if a property can only be found until we reach the global object.
![Page 31: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/31.jpg)
31
From jQuery Source Code
• Above code is taken from jQuery's source code.• It makes undefined a local variable instead of a
property in the global object.– Faster due to shorter search path for this property
![Page 32: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/32.jpg)
32
arguments
• arguments is an array-like object that contains actual parameters when a function is invoked.– arguments.length, arguments[0]– Use Array.prototype.slice.apply(arguments) to convert
it to a true array.
• Use arguments to simulate function overloading.– Apply different behaviors according to number and typ
es of parameters.
• arguments.callee refers to the caller function, can be used to invoke an anonymous function recursively.
![Page 33: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/33.jpg)
33
this
• this is a JavaScript keyword, points to another object.– Can be used in function body. Placed before an identifier.
– Resolving of this identifier starts from the object referenced by this.
• The value of this depends on how the function is invoked.– As an object's property, e.g. myObj.myFunc()
• this refers to the object, e.g. myObj
– Not as an object's property, e.g. myFunc()• this refers to the global object
– After new operator, e.g. new User()• this refers to the newly created object
– Use apply and call specify a value • this refers to that value
![Page 34: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/34.jpg)
34
Closure? What is it?
![Page 35: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/35.jpg)
35
Closure
• Closure is an expression, typically a function.• It has free variables and an execution environme
nt to close the expression. – The execution environment is responsible for resolvin
g value of variables.
• Closure is easy to create, intentionally or accidentally– Return the reference of an inner function.– Inner function still can be invoked even after the outer
function exits.
![Page 36: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/36.jpg)
36
Understand Closure
• The key to understand how closure works is Scope Chain.
• The execution environment maintains a function's scope chain.– The scope chain is still accessible even thoug
h the outer function exits.– The objects in the scope chain retain their stat
es when the outer function exits.
![Page 37: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/37.jpg)
37
A Closure Example
• Outer function addBy returns a reference of its inner function add.
• When function add is invoked, it still has access to other objects in its scope chain.
ActivationObject(add)
ActivationObject
(addBy)
GlobalObject
firstsecond
Scope chain when add is invoked
![Page 38: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/38.jpg)
38
Closure and Encapsulation
• Use closure to create private properties.• Private properties enable encapsulation.• Closure can be used to protect internal states an
d guard against malicious actions.
• Use an anonymous function to create a closure.• Property currentId is encapsulatedin this closure.
![Page 39: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/39.jpg)
39
Use closure is a challenge to code readability. Be prepared.
![Page 40: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/40.jpg)
40
References
• ECMAScript 3rd specification
• JavaScript : The Good Parts
• Learning Advanced JavaScript
• JavaScript Closures
• JavaScript技巧与高级特性
![Page 41: Advanced JavaScript](https://reader036.vdocuments.mx/reader036/viewer/2022062513/555ae324d8b42a4c7d8b45b7/html5/thumbnails/41.jpg)
41
Creative Commons Images Used
• myklroventine/3261364899/
• yhancik/354788792/
• trashit_t-shirt/2171336265/
• huge09/4276632202/
• brianarn/265152959/
• carlosporto/775089650/
All available at http://www.flickr.com/photos/