SlideShare a Scribd company logo
Advanced JavaScript Douglas Crockford © 2006 Douglas Crockford
Coming Up Inheritance Modules Debugging Efficiency JSON
Inheritance Inheritance is object-oriented code reuse. Two Schools: Classical Prototypal
Classical Inheritance Objects are instances of Classes. A Class inherits from another Class.
Prototypal Inheritance Class-free. Objects inherit from objects. An object contains a  secret link  to another object. Mozilla calls it  __proto__ . var newObject = object(oldObject); newObject oldObject __proto__
Prototypal Inheritance var  oldObject  = { firstMethod: function () {...}, secondMethod: function () {...} }; var  newObject  = object( oldObject ); newObject .thirdMethod = function () {...}; var  myDoppelganger  = object( newObject ); myDoppelganger .firstMethod();
Prototypal Inheritance If an object has a  foo  property, then the chain will not be consulted when accessing member  foo . newObject.foo  newObject['foo'] oldObject newObject 2 foo 1 foo
Prototypal Inheritance If access of a member of  newObject  fails, then search for the member in  oldObject . If that fails, then search for the member in  Object.prototype . newObject oldObject
Prototypal Inheritance Changes in  oldObject  may be immediately visible in  newObject . Changes to  newObject  have no effect on  oldObject . newObject oldObject
Prototypal Inheritance oldObject  can be the prototype for an unlimited number of objects which will all inherit its properties. newObject oldObject
Prototypal Inheritance newObject  can be the prototype for an unlimited number of even newer objects. There is no limit to the length of the chain (except common sense). oldObject myDoppelganger = object(newObject); newObject
Augmentation Using the  object  function, we can quickly produce new objects that have the same state and behavior as existing objects. We can then augment each of the instances by assigning new methods and members.
Pseudoclassical A prototypal inheritance language should have an operator like the  object  function, which makes a new object using an existing object as its prototype. JavaScript instead uses operators that look classical, but behave prototypally. They tried to have it both ways.
Pseudoclassical Three mechanisms: Constructor  functions. The  new  operator. The  prototype  member of functions.
new  operator function  Constructor () { this.member = initializer; return this;  // optional } Constructor .prototype.firstMethod =  function (a, b) {...}; Constructor .prototype.secondMethod =  function (c) {...};  var newobject = new  Constructor ();
Constructor When functions are designed to be used with  new , they are called constructors. Constructors are used to make objects of a type or class. JavaScript's notation can get a little strange because it is trying to look like the old familiar classical pattern, while also trying to be something really different.
new  operator new  Constructor ()  returns a new object with a link to  Constructor .prototype . var newObject = new  Constructor (); Constructor .prototype newObject
new  operator The  Constructor ()  function is passed the new object in the  this  variable. This allows the  Constructor  function to customize the new object. Constructor .prototype newobject
Warning The  new  operator is  required  when calling a Constructor. If  new  is omitted, the global object is clobbered by the constructor, and then the global object is returned instead of a new instance.
prototype When a function object is created, it is given a  prototype  member which is an object containing a  constructor  member which is a reference to the function object.
prototype You can add other members to a function's  prototype . These members will be linked into objects that are produced by calling the function with the  new  operator. This allows for adding constants and methods to every object produced, without the objects having to be enlarged to contain them. Differential Inheritance.
method  method Function.prototype. method  =  function (name, func) {  this.prototype[name] = func;  return this;  };  Constructor. method ('first_method',  function (a, b) {...}). method ('second_method', function (c) {...});
Pseudoclassical Inheritance Classical inheritance can be simulated by assigning an object created by one constructor to the prototype member of another. This does not work exactly like the classical model. function  BiggerConstructor () {}; BiggerConstructor .prototype =  new MyConstructor();
Example function  Gizmo (id) { this.id = id; } Gizmo .prototype.toString = function () { return "gizmo " + this.id; };
Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return "gizmo " + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
Inheritance If we replace the original prototype object with an instance of an object of another class, then we can inherit another class's stuff.
Example function  Hoozit (id) { this.id = id; } Hoozit .prototype = new  Gizmo (); Hoozit .prototype.test = function (id) { return this.id === id; };
Example function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; Gizmo Hoozit new Hoozit( string ) prototype prototype function test constructor function toString constructor string id
Example function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; Gizmo Hoozit new Hoozit( string ) prototype prototype function test constructor function toString constructor string id
object  function A prototypal inheritance language should have an operator like the  object  function, which makes a new object using an existing object as its prototype.
object  function function object(o) { function F() {} F.prototype = o; return new F(); }
object  function F function object(o) { function F() {} F.prototype = o; return new F(); }  newobject = object(oldobject) prototype constructor
object  function F function object(o) { function F() {} F.prototype = o; return new F(); }  newobject = object(oldobject) oldobject prototype constructor
object  function F newobject function object(o) { function F() {} F.prototype = o; return new F(); }  newobject = object(oldobject) oldobject prototype
object  function newobject function object(o) { function F() {} F.prototype = o; return new F(); }  newobject = object(oldobject) oldobject
Public Method A Public Method is a function that uses  this  to access its object. A Public Method can be reused with many "classes".
Public Methods function (string) {  return  this .member + string; }  We can put this function in any object at it works. Public methods work extremely well with prototypal inheritance and with pseudoclassical inheritance.
Singletons There is no need to produce a class-like constructor for an object that will have exactly one instance. Instead, simply use an object literal.
Singletons var singleton = { firstMethod: function (a, b) { ... }, secondMethod: function (c) { ... } };
Singletons The methods of a singleton can enjoy access to shared private data and private methods.
Functions Functions are used as Functions Methods Constructors Classes Modules
Module Variables defined in a module are only visible in the module. Functions have scope. Variables defined in a function only visible in the function. Functions can be used a module containers.
Global variables are evil Functions within an application can clobber each other. Cooperating applications can clobber each other. Use of the global namespace must be minimized.
Singletons var singleton =  function () { var  privateVariable ; function  privateFunction (x) { ... privateVariable ... } return  { firstMethod: function (a, b) { ... privateVariable ... }, secondMethod: function (c) { ... privateFunction ()... } } ; }() ;
Applications are Singletons YAHOO.MyProperty =  function () { var  privateVariable ; function  privateFunction (x) { ... privateVariable ... } return  { firstMethod: function (a, b) { ... privateVariable ... }, secondMethod: function (c) { ... privateFunction ()... } } ; }() ;
Privileged Method A Privileged Method is a function that has access to secret information. A Privileged Method has access to private variables and private methods. A Privileged Method obtains its secret information through closure.
Power Constructor Put the singleton module pattern in constructor function, and we have a power constructor pattern. Make a new object somehow. Augment it. Return it.
function powerConstructor() { var  that  =  object(oldObject) , privateVariable ; function  privateFunction (x) {} that .firstMethod = function (a, b) { ... privateVariable ... }; that .secondMethod = function (c) { ... privateFunction ()... }; return  that ; }
Power Constructor Public methods (from the prototype) var  that  = object(my_base); Private variables (var) Private methods (inner functions) Privileged methods ( that ...) No need to use  new myObject = power_constructor();
Parasitic Inheritance A power constructor calls another constructor, takes the result, augments it, and returns it as though it did all the work.
function symbol(s, p) { return { id: s,  lbp: p,  value: s }; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = true; x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; }
Pseudoclassical Inheritance function  Gizmo (id) { this.id = id; } Gizmo .prototype.toString = function () { return "gizmo " + this.id; }; function  Hoozit (id) { this.id = id; } Hoozit .prototype = new  Gizmo (); Hoozit .prototype.test = function (id) { return this.id === id; };
Parasitic Inheritance function  gizmo (id) { return { id: id, toString: function () { return "gizmo " + this.id; } }; } function  hoozit (id) { var  that  =  gizmo (id); that .test = function (testid) { return testid === this.id; }; return  that ; }
Secrets function gizmo( id ) { return { toString: function () { return "gizmo " +  id ; } }; } function hoozit( id ) { var  that  = gizmo( id ); that .test = function (testid) { return testid ===  id ; }; return  that ; }
Shared Secrets function gizmo(id,  secret ) { secret  =  secret  || {}; secret .id = id; return { toString: function () { return "gizmo " +  secret .id; }; }; } function hoozit(id) { var  secret  = {},  /*final*/ that  = gizmo(id,  secret ); that .test = function (testid) { return testid ===  secret .id; }; return  that ; }
Super Methods function hoozit(id) { var secret = {}, that  = gizmo(id, secret), super_toString  =  that .toString; that .test = function (testid) { return testid === secret.id; }; that .toString = function () { return  super_toString .apply( that , []); }; return  that ; }
Inheritance Patterns Prototypal Inheritance works really well with  public  methods. Parasitic Inheritance works really well with  privileged  and  private  and  public  methods. Pseudoclassical Inheritance for elderly programmers who are old  and set in their ways.
Working with the Grain Pseudoclassical  patterns are less effective than  prototypal  patterns or  parasitic  patterns. Formal classes are not needed for reuse or extension. Be shallow. Deep hierarchies are not effective.
later  method The  later  method causes a method on the object to be invoked in the future. my_object.later(1000, "erase", true);
later  method Object.prototype.later =  function (msec, method) {      var that = this, args = Array.prototype.slice. apply(arguments, [2]);  if (typeof method === 'string') {  method = that[method];  }   setTimeout( function () {  method.apply(that, args);  } , msec);  return that;  };
Multiples When assigning functions in a loop, be aware that all of the functions are bound to the same closure. This can be avoided by using a factor function to produce unique bindings.
Multiples for (i ...) { var div_id = divs[i].id; divs[i].onmouseover =  function () { show_element_id(div_id); } ; } for (i ...) { var div_id = divs[i].id; divs[i].onmouseover =  function (id) { return   function () { show_element_id(id); } ; } (div_id); }
Debugging As programs get larger and more complex, debugging tools are required for efficient development.
Debugging IE  Microsoft Script Debugger Office 2003 Visual Studio Mozilla Venkman Firebug Safari Drosera
Microsoft Script Debugger
Microsoft Script Debugger
Microsoft Script Debugger
Microsoft Script Debugger
Venkman
Venkman
Venkman
debugger The  debugger  statement can be used as a programmable breakpoint. if (something === 'wrong') { debugger; }
Performance Provide a good experience. Be respectful of our customer's time. Hoare's Dictum:  Premature optimization is the root of all evil.
Efficiency The first priority must always be correctness. Optimize when necessary. Consider algorithmic improvements O  (n)  v   O  (n log n)  v   O  (n 2 ) Watch for limits.
Coding Efficiency Common subexpression removal Loop invariant removal
Before for (var i = 0; i <  divs.length ; i += 1) { divs[i].style. color = &quot;black&quot;;  divs[i].style. border =  thickness +  'px solid blue' ;  divs[i].style. backgroundColor = &quot;white&quot;;  }
After var  border  =  thickness + 'px solid blue' , nrDivs  =  divs.length ; for (var i = 0; i <  nrDivs ; i += 1) { var  ds  =  divs[i].style ; ds .color = &quot;black&quot;;  ds .border =  border ;  ds .backgroundColor = &quot;white&quot;;  }
Strings Concatenation with  + Each operation allocates memory foo = a + b; Concatenate with array .join('') The contents of an array are concatenated into a single string foo = [a, b].join('');
Minification vs Obfuscation Reduce the amount of source code to reduce download time. Minification deletes whitespace and comments. Obfuscation also changes the names of things. Obfuscation can introduce bugs. Never use tools that cause bugs if you can avoid it. http://www.crockford.com/javascript/jsmin.html
JSON JavaScript Object Notation. A Data Interchange Format. Text-based. Light-weight. Easy to parse. Language Independent. A Subset of ECMA-262 ECMAScript Third Edition.
Object
Array
Value
String
Number
Advanced JavaScript Douglas Crockford © 2006 Douglas Crockford
Ad

More Related Content

What's hot (20)

Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
Teksify
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
John Hunter
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Js: master prototypes
Js: master prototypesJs: master prototypes
Js: master prototypes
Barak Drechsler
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Javascript talk
Javascript talkJavascript talk
Javascript talk
Suresh Jayanty
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2
Hariz Mustafa
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
schwaa
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
Vince Vo
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
Teksify
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
John Hunter
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
gourav kottawar
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2Lecture06 methods for-making_data_structures_v2
Lecture06 methods for-making_data_structures_v2
Hariz Mustafa
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
schwaa
 
Java căn bản - Chapter2
Java căn bản - Chapter2Java căn bản - Chapter2
Java căn bản - Chapter2
Vince Vo
 

Viewers also liked (13)

MySQL Proxy
MySQL ProxyMySQL Proxy
MySQL Proxy
Manikanda kumar
 
Pre-Cal 40S Slides October 2, 2007
Pre-Cal 40S Slides October 2, 2007Pre-Cal 40S Slides October 2, 2007
Pre-Cal 40S Slides October 2, 2007
Darren Kuropatwa
 
Liderazgo
LiderazgoLiderazgo
Liderazgo
guestdeb64c
 
Build your online reputation with Venyo.org
Build your online reputation with Venyo.orgBuild your online reputation with Venyo.org
Build your online reputation with Venyo.org
venyo
 
Own It Test Presentation
Own It Test PresentationOwn It Test Presentation
Own It Test Presentation
ownit
 
Enter Text
Enter TextEnter Text
Enter Text
eugelugo
 
Crueldad irani
Crueldad iraniCrueldad irani
Crueldad irani
joselgh
 
Wavesin2 Dreview
Wavesin2 DreviewWavesin2 Dreview
Wavesin2 Dreview
ekozoriz
 
Designing Ajax Principles And Patterns For Designing Rich Internet Appl...
Designing  Ajax  Principles And  Patterns For Designing  Rich  Internet  Appl...Designing  Ajax  Principles And  Patterns For Designing  Rich  Internet  Appl...
Designing Ajax Principles And Patterns For Designing Rich Internet Appl...
Manikanda kumar
 
PHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing pluginPHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing plugin
Ulf Wendel
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
Manikanda kumar
 
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScaleThe Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
Colin Charles
 
Pre-Cal 40S Slides October 2, 2007
Pre-Cal 40S Slides October 2, 2007Pre-Cal 40S Slides October 2, 2007
Pre-Cal 40S Slides October 2, 2007
Darren Kuropatwa
 
Build your online reputation with Venyo.org
Build your online reputation with Venyo.orgBuild your online reputation with Venyo.org
Build your online reputation with Venyo.org
venyo
 
Own It Test Presentation
Own It Test PresentationOwn It Test Presentation
Own It Test Presentation
ownit
 
Enter Text
Enter TextEnter Text
Enter Text
eugelugo
 
Crueldad irani
Crueldad iraniCrueldad irani
Crueldad irani
joselgh
 
Wavesin2 Dreview
Wavesin2 DreviewWavesin2 Dreview
Wavesin2 Dreview
ekozoriz
 
Designing Ajax Principles And Patterns For Designing Rich Internet Appl...
Designing  Ajax  Principles And  Patterns For Designing  Rich  Internet  Appl...Designing  Ajax  Principles And  Patterns For Designing  Rich  Internet  Appl...
Designing Ajax Principles And Patterns For Designing Rich Internet Appl...
Manikanda kumar
 
PHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing pluginPHP mysqlnd connection multiplexing plugin
PHP mysqlnd connection multiplexing plugin
Ulf Wendel
 
MySQL Query And Index Tuning
MySQL Query And Index TuningMySQL Query And Index Tuning
MySQL Query And Index Tuning
Manikanda kumar
 
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScaleThe Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
Colin Charles
 
Ad

Similar to Advanced Javascript (20)

Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Chapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdfChapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdf
joshua211619
 
Unit ii
Unit   iiUnit   ii
Unit ii
donny101
 
Object Oriented Programming notes provided
Object Oriented Programming notes providedObject Oriented Programming notes provided
Object Oriented Programming notes provided
dummydoona
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
Design patterns
Design patternsDesign patterns
Design patterns
Anas Alpure
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
Gunjan Kumar
 
Week 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptxWeek 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
Julie Iskander
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Defining method in JavaScript object.pptx
Defining method in JavaScript object.pptxDefining method in JavaScript object.pptx
Defining method in JavaScript object.pptx
Steins18
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Chapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdfChapter- 2 Introduction to Class and Object.pdf
Chapter- 2 Introduction to Class and Object.pdf
joshua211619
 
Object Oriented Programming notes provided
Object Oriented Programming notes providedObject Oriented Programming notes provided
Object Oriented Programming notes provided
dummydoona
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
Phúc Đỗ
 
Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02Prototype 120102020133-phpapp02
Prototype 120102020133-phpapp02
plutoone TestTwo
 
Week 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptxWeek 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Defining method in JavaScript object.pptx
Defining method in JavaScript object.pptxDefining method in JavaScript object.pptx
Defining method in JavaScript object.pptx
Steins18
 
Ad

Recently uploaded (20)

Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
The Microsoft Excel Parts Presentation.pdf
The Microsoft Excel Parts Presentation.pdfThe Microsoft Excel Parts Presentation.pdf
The Microsoft Excel Parts Presentation.pdf
YvonneRoseEranista
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Web and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in RajpuraWeb and Graphics Designing Training in Rajpura
Web and Graphics Designing Training in Rajpura
Erginous Technology
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
The Microsoft Excel Parts Presentation.pdf
The Microsoft Excel Parts Presentation.pdfThe Microsoft Excel Parts Presentation.pdf
The Microsoft Excel Parts Presentation.pdf
YvonneRoseEranista
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 

Advanced Javascript

  • 1. Advanced JavaScript Douglas Crockford © 2006 Douglas Crockford
  • 2. Coming Up Inheritance Modules Debugging Efficiency JSON
  • 3. Inheritance Inheritance is object-oriented code reuse. Two Schools: Classical Prototypal
  • 4. Classical Inheritance Objects are instances of Classes. A Class inherits from another Class.
  • 5. Prototypal Inheritance Class-free. Objects inherit from objects. An object contains a secret link to another object. Mozilla calls it __proto__ . var newObject = object(oldObject); newObject oldObject __proto__
  • 6. Prototypal Inheritance var oldObject = { firstMethod: function () {...}, secondMethod: function () {...} }; var newObject = object( oldObject ); newObject .thirdMethod = function () {...}; var myDoppelganger = object( newObject ); myDoppelganger .firstMethod();
  • 7. Prototypal Inheritance If an object has a foo property, then the chain will not be consulted when accessing member foo . newObject.foo newObject['foo'] oldObject newObject 2 foo 1 foo
  • 8. Prototypal Inheritance If access of a member of newObject fails, then search for the member in oldObject . If that fails, then search for the member in Object.prototype . newObject oldObject
  • 9. Prototypal Inheritance Changes in oldObject may be immediately visible in newObject . Changes to newObject have no effect on oldObject . newObject oldObject
  • 10. Prototypal Inheritance oldObject can be the prototype for an unlimited number of objects which will all inherit its properties. newObject oldObject
  • 11. Prototypal Inheritance newObject can be the prototype for an unlimited number of even newer objects. There is no limit to the length of the chain (except common sense). oldObject myDoppelganger = object(newObject); newObject
  • 12. Augmentation Using the object function, we can quickly produce new objects that have the same state and behavior as existing objects. We can then augment each of the instances by assigning new methods and members.
  • 13. Pseudoclassical A prototypal inheritance language should have an operator like the object function, which makes a new object using an existing object as its prototype. JavaScript instead uses operators that look classical, but behave prototypally. They tried to have it both ways.
  • 14. Pseudoclassical Three mechanisms: Constructor functions. The new operator. The prototype member of functions.
  • 15. new operator function Constructor () { this.member = initializer; return this; // optional } Constructor .prototype.firstMethod = function (a, b) {...}; Constructor .prototype.secondMethod = function (c) {...}; var newobject = new Constructor ();
  • 16. Constructor When functions are designed to be used with new , they are called constructors. Constructors are used to make objects of a type or class. JavaScript's notation can get a little strange because it is trying to look like the old familiar classical pattern, while also trying to be something really different.
  • 17. new operator new Constructor () returns a new object with a link to Constructor .prototype . var newObject = new Constructor (); Constructor .prototype newObject
  • 18. new operator The Constructor () function is passed the new object in the this variable. This allows the Constructor function to customize the new object. Constructor .prototype newobject
  • 19. Warning The new operator is required when calling a Constructor. If new is omitted, the global object is clobbered by the constructor, and then the global object is returned instead of a new instance.
  • 20. prototype When a function object is created, it is given a prototype member which is an object containing a constructor member which is a reference to the function object.
  • 21. prototype You can add other members to a function's prototype . These members will be linked into objects that are produced by calling the function with the new operator. This allows for adding constants and methods to every object produced, without the objects having to be enlarged to contain them. Differential Inheritance.
  • 22. method method Function.prototype. method = function (name, func) { this.prototype[name] = func; return this; }; Constructor. method ('first_method', function (a, b) {...}). method ('second_method', function (c) {...});
  • 23. Pseudoclassical Inheritance Classical inheritance can be simulated by assigning an object created by one constructor to the prototype member of another. This does not work exactly like the classical model. function BiggerConstructor () {}; BiggerConstructor .prototype = new MyConstructor();
  • 24. Example function Gizmo (id) { this.id = id; } Gizmo .prototype.toString = function () { return &quot;gizmo &quot; + this.id; };
  • 25. Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return &quot;gizmo &quot; + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
  • 26. Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return &quot;gizmo &quot; + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
  • 27. Example function Gizmo(id) { this.id = id; } Gizmo.prototype.toString = function () { return &quot;gizmo &quot; + this.id; }; new Gizmo( string ) Gizmo Object prototype string id function toString constructor prototype function toString constructor
  • 28. Inheritance If we replace the original prototype object with an instance of an object of another class, then we can inherit another class's stuff.
  • 29. Example function Hoozit (id) { this.id = id; } Hoozit .prototype = new Gizmo (); Hoozit .prototype.test = function (id) { return this.id === id; };
  • 30. Example function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; Gizmo Hoozit new Hoozit( string ) prototype prototype function test constructor function toString constructor string id
  • 31. Example function Hoozit(id) { this.id = id; } Hoozit.prototype = new Gizmo(); Hoozit.prototype.test = function (id) { return this.id === id; }; Gizmo Hoozit new Hoozit( string ) prototype prototype function test constructor function toString constructor string id
  • 32. object function A prototypal inheritance language should have an operator like the object function, which makes a new object using an existing object as its prototype.
  • 33. object function function object(o) { function F() {} F.prototype = o; return new F(); }
  • 34. object function F function object(o) { function F() {} F.prototype = o; return new F(); } newobject = object(oldobject) prototype constructor
  • 35. object function F function object(o) { function F() {} F.prototype = o; return new F(); } newobject = object(oldobject) oldobject prototype constructor
  • 36. object function F newobject function object(o) { function F() {} F.prototype = o; return new F(); } newobject = object(oldobject) oldobject prototype
  • 37. object function newobject function object(o) { function F() {} F.prototype = o; return new F(); } newobject = object(oldobject) oldobject
  • 38. Public Method A Public Method is a function that uses this to access its object. A Public Method can be reused with many &quot;classes&quot;.
  • 39. Public Methods function (string) { return this .member + string; } We can put this function in any object at it works. Public methods work extremely well with prototypal inheritance and with pseudoclassical inheritance.
  • 40. Singletons There is no need to produce a class-like constructor for an object that will have exactly one instance. Instead, simply use an object literal.
  • 41. Singletons var singleton = { firstMethod: function (a, b) { ... }, secondMethod: function (c) { ... } };
  • 42. Singletons The methods of a singleton can enjoy access to shared private data and private methods.
  • 43. Functions Functions are used as Functions Methods Constructors Classes Modules
  • 44. Module Variables defined in a module are only visible in the module. Functions have scope. Variables defined in a function only visible in the function. Functions can be used a module containers.
  • 45. Global variables are evil Functions within an application can clobber each other. Cooperating applications can clobber each other. Use of the global namespace must be minimized.
  • 46. Singletons var singleton = function () { var privateVariable ; function privateFunction (x) { ... privateVariable ... } return { firstMethod: function (a, b) { ... privateVariable ... }, secondMethod: function (c) { ... privateFunction ()... } } ; }() ;
  • 47. Applications are Singletons YAHOO.MyProperty = function () { var privateVariable ; function privateFunction (x) { ... privateVariable ... } return { firstMethod: function (a, b) { ... privateVariable ... }, secondMethod: function (c) { ... privateFunction ()... } } ; }() ;
  • 48. Privileged Method A Privileged Method is a function that has access to secret information. A Privileged Method has access to private variables and private methods. A Privileged Method obtains its secret information through closure.
  • 49. Power Constructor Put the singleton module pattern in constructor function, and we have a power constructor pattern. Make a new object somehow. Augment it. Return it.
  • 50. function powerConstructor() { var that = object(oldObject) , privateVariable ; function privateFunction (x) {} that .firstMethod = function (a, b) { ... privateVariable ... }; that .secondMethod = function (c) { ... privateFunction ()... }; return that ; }
  • 51. Power Constructor Public methods (from the prototype) var that = object(my_base); Private variables (var) Private methods (inner functions) Privileged methods ( that ...) No need to use new myObject = power_constructor();
  • 52. Parasitic Inheritance A power constructor calls another constructor, takes the result, augments it, and returns it as though it did all the work.
  • 53. function symbol(s, p) { return { id: s, lbp: p, value: s }; } function delim(s) { return symbol(s, 0); } function stmt(s, f) { var x = delim(s); x.identifier = true; x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; }
  • 54. Pseudoclassical Inheritance function Gizmo (id) { this.id = id; } Gizmo .prototype.toString = function () { return &quot;gizmo &quot; + this.id; }; function Hoozit (id) { this.id = id; } Hoozit .prototype = new Gizmo (); Hoozit .prototype.test = function (id) { return this.id === id; };
  • 55. Parasitic Inheritance function gizmo (id) { return { id: id, toString: function () { return &quot;gizmo &quot; + this.id; } }; } function hoozit (id) { var that = gizmo (id); that .test = function (testid) { return testid === this.id; }; return that ; }
  • 56. Secrets function gizmo( id ) { return { toString: function () { return &quot;gizmo &quot; + id ; } }; } function hoozit( id ) { var that = gizmo( id ); that .test = function (testid) { return testid === id ; }; return that ; }
  • 57. Shared Secrets function gizmo(id, secret ) { secret = secret || {}; secret .id = id; return { toString: function () { return &quot;gizmo &quot; + secret .id; }; }; } function hoozit(id) { var secret = {}, /*final*/ that = gizmo(id, secret ); that .test = function (testid) { return testid === secret .id; }; return that ; }
  • 58. Super Methods function hoozit(id) { var secret = {}, that = gizmo(id, secret), super_toString = that .toString; that .test = function (testid) { return testid === secret.id; }; that .toString = function () { return super_toString .apply( that , []); }; return that ; }
  • 59. Inheritance Patterns Prototypal Inheritance works really well with public methods. Parasitic Inheritance works really well with privileged and private and public methods. Pseudoclassical Inheritance for elderly programmers who are old and set in their ways.
  • 60. Working with the Grain Pseudoclassical patterns are less effective than prototypal patterns or parasitic patterns. Formal classes are not needed for reuse or extension. Be shallow. Deep hierarchies are not effective.
  • 61. later method The later method causes a method on the object to be invoked in the future. my_object.later(1000, &quot;erase&quot;, true);
  • 62. later method Object.prototype.later = function (msec, method) {     var that = this, args = Array.prototype.slice. apply(arguments, [2]); if (typeof method === 'string') { method = that[method]; } setTimeout( function () { method.apply(that, args); } , msec); return that; };
  • 63. Multiples When assigning functions in a loop, be aware that all of the functions are bound to the same closure. This can be avoided by using a factor function to produce unique bindings.
  • 64. Multiples for (i ...) { var div_id = divs[i].id; divs[i].onmouseover = function () { show_element_id(div_id); } ; } for (i ...) { var div_id = divs[i].id; divs[i].onmouseover = function (id) { return function () { show_element_id(id); } ; } (div_id); }
  • 65. Debugging As programs get larger and more complex, debugging tools are required for efficient development.
  • 66. Debugging IE Microsoft Script Debugger Office 2003 Visual Studio Mozilla Venkman Firebug Safari Drosera
  • 74. debugger The debugger statement can be used as a programmable breakpoint. if (something === 'wrong') { debugger; }
  • 75. Performance Provide a good experience. Be respectful of our customer's time. Hoare's Dictum: Premature optimization is the root of all evil.
  • 76. Efficiency The first priority must always be correctness. Optimize when necessary. Consider algorithmic improvements O (n) v O (n log n) v O (n 2 ) Watch for limits.
  • 77. Coding Efficiency Common subexpression removal Loop invariant removal
  • 78. Before for (var i = 0; i < divs.length ; i += 1) { divs[i].style. color = &quot;black&quot;; divs[i].style. border = thickness + 'px solid blue' ; divs[i].style. backgroundColor = &quot;white&quot;; }
  • 79. After var border = thickness + 'px solid blue' , nrDivs = divs.length ; for (var i = 0; i < nrDivs ; i += 1) { var ds = divs[i].style ; ds .color = &quot;black&quot;; ds .border = border ; ds .backgroundColor = &quot;white&quot;; }
  • 80. Strings Concatenation with + Each operation allocates memory foo = a + b; Concatenate with array .join('') The contents of an array are concatenated into a single string foo = [a, b].join('');
  • 81. Minification vs Obfuscation Reduce the amount of source code to reduce download time. Minification deletes whitespace and comments. Obfuscation also changes the names of things. Obfuscation can introduce bugs. Never use tools that cause bugs if you can avoid it. http://www.crockford.com/javascript/jsmin.html
  • 82. JSON JavaScript Object Notation. A Data Interchange Format. Text-based. Light-weight. Easy to parse. Language Independent. A Subset of ECMA-262 ECMAScript Third Edition.
  • 84. Array
  • 85. Value
  • 88. Advanced JavaScript Douglas Crockford © 2006 Douglas Crockford