Advanced JavaScript


Published on

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.

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Advanced JavaScript

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