SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
JavaScript
                            Do you speak it!


Tuesday, August 2, 2011
!"#$%&'(&'&)*
                   *
                   +,&-*.%/012%*3%*4&5#663*
                   78(9::;#%7/<=$&>:"#$%&'(&'&)*




Tuesday, August 2, 2011
“The world’s most

                                  misunderstood

                          programming language”




Tuesday, August 2, 2011
We’ll talk about

                          why JavaScript is the most misunderstood
                          programming language

                          Object Oriented Programming in JavaScript

                          function scope, closures, circular references

                          making the web a little faster



Tuesday, August 2, 2011
JavaScript

                          aka Mocha

                                        aka LiveScript

                          aka JScript
                                              aka ECMAScript




Tuesday, August 2, 2011
Java... Script?


                          somehow related to Java?

                          maybe a subset?

                          less capable interpreted version of Java?




Tuesday, August 2, 2011
Java... Script?


                          developed by Netscape in 1997 (vs. 3.0 in 1999)

                          Java prefix intended to create confusion

                          JavaScript is not interpreted Java




Tuesday, August 2, 2011
Design errors
                                                           1 + “1” = ?
                                                           1 + +”1” = ?
                          overloading “+” means both addition and
                          string concatenation with type conversion

                          error-prone “with” statement

                          reserved word policies are much too strict

                          semicolon insertion was “a huge mistake”



Tuesday, August 2, 2011
Bad implementations


                          earlier implementations were buggy

                          embedded horribly in browsers

                          did not respect the ECMA standard




Tuesday, August 2, 2011
Evolution

                          first versions of JavaScript were quite weak

                          no exception handling, inner functions

                          in its present form, it’s a full OOP language

                          ECMAScript 5.1




Tuesday, August 2, 2011
Overview

                          types and operators, core objects, methods

                          does not have classes, but this functionality is
                          accomplished with object prototypes

                          functions are objects (and can be passed
                          around as parameters)




Tuesday, August 2, 2011
(Loosely) Types
                                                          typeof
                          Number                          instanceof

                          String

                          Boolean

                          Object (Function, Array, Date, RegExp)

                          Null

                          Undefined


Tuesday, August 2, 2011
Lisp in C’s clothing


                          C-like syntax (curly braces, for statement...)

                          appears to be a procedural language

                          it’s actually a functional language!




Tuesday, August 2, 2011
Haskell vs. JS
          palindr :: [Int] -> Bool
          palindr [] = True
          palindr [x] = True
          palindr xs = (head xs == last xs)
            && palindr (tail (init xs))

          function palindr(xs) {
            var i, len = xs.length;
            for (i = 0; i < len / 2; i++)
              if (xs[i] !== xs[len - i - 1])
                return false;

                return true;
          }

Tuesday, August 2, 2011
Objects
                          JavaScript is fundamentally about objects

                          usually implemented as hashtables

                          objects are created using constructors

                          use a namespace for them (don’t modify
                          objects you don’t own)

                          use JS sugar: var obj = {}; and var arr = [];


Tuesday, August 2, 2011
OOP
                                             class Dog {
                                               public string name = “”;
                                               public int yearsOld = 0;
                          polymorphism           void bark(int times);
                                                 void bark(float volume);
                          encapsulation          void sleep();
                                             }
                          inheritance
                                             class Pudel : Dog {
                                               public int cuteness = 5;
                          abstractization    }

                                             Dog pinky = new Dog();
                                             Dog leyla = new Pudel();

Tuesday, August 2, 2011
Objects in JavaScript
          MyNamespace.Dog = function(){
             this.name = “”;
             this.yearsOld = 0;
          };

          MyNamespace.Dog.prototype = {
             bark: function(param){
             },
             sleep: function(){
             }
          };

          var pinky = new Dog();
          var leyla = new Dog();
          leyla.cuteness = 5;

Tuesday, August 2, 2011
Objects in JavaScript
          MyNamespace.Dog = function(){
             this.name = “”;
             this.yearsOld = 0;
          };                              no private members?

          MyNamespace.Dog.prototype = {
             bark: function(param){
             },
             sleep: function(){
             }
          };

          var pinky = new Dog();
          var leyla = new Dog();
          leyla.cuteness = 5;

Tuesday, August 2, 2011
Closures
          function foo(a, b){
            function bar() {
              return a + b;
            }

                return bar();
                                    var res1 = foo(5, 2);
          }
                                    var res2 = foo2(5, 2);
          function foo2(a, b){
                                    var res3 = res2(3);
            function bar(c) {
              return a + b + c;
            }

                return bar;
          }

Tuesday, August 2, 2011
Private members
          MyNamespace.Dog = function(){
            var name = “”;
            var yearsOld = 0;

                this.bark = function(param){
                   if (“Number” === typeof param) {
                   }
                   else {
                   }
                };
                this.sleep = function(){
                };
          };

          var pinky = new Dog();

Tuesday, August 2, 2011
Private members
          MyNamespace.Dog = function(paramName, paramYearsOld){
            var name = paramName;
            var yearsOld = paramYearsOld;

                this.bark = function(param){
                };
                this.sleep = function(){
                };

                get nrYearsOld(){
                   return yearsOld;
                };
          };

          var pinky = new Dog();
          console.log(pinky.nrYearsOld);
Tuesday, August 2, 2011
Why is JavaScript
                                slow?


                           Bad compilation?



Tuesday, August 2, 2011
Why is JavaScript
                                slow?


                           No compilation!*



Tuesday, August 2, 2011
Why is JavaScript
                                slow?


                           No compilation!*

             *yes, interpreters are a lot smarter these days, but..

Tuesday, August 2, 2011
Scope chains
          function scope1(){
            var elem2;

                function scope2(){
                  var elem2;

                      function scope3(){
                        var elem3;
                        var func = window.alert;

                          return {
                            something: elem4,
                            somethingElse: elem5
                          }
                      }
                }
          }
Tuesday, August 2, 2011
Memory leaks
          function leakMemory(){
            var elem = somethingThatOccupiesLotsOfMemory;

                function inner(){
                };

                return inner;
          }

          var res1 = leakMemory();
          var res2 = leakMemory();



Tuesday, August 2, 2011
Circular references
          function leakMemory(){
            var elem = document.getElementById(“someId”);

                elem.onclick = function(){
                };
          }




Tuesday, August 2, 2011
Circular references
          function dontLeakMemory(){
            var elem = document.getElementById(“someId”);

                elem.onclick = function(){
                };

                elem = null;
          }




Tuesday, August 2, 2011
Circular references
          function leakMemory(){
            var elem = document.getElementById(“someId”);

                elem.onclick = function(){
                };

                return elem;
          }




Tuesday, August 2, 2011
Circular references
          function dontLeakMemory(){
            var elem = document.getElementById(“someId”);

                elem.onclick = function(){
                };

                try {
                  return elem;
                }
                finally {
                  elem = null;
                }
          }

Tuesday, August 2, 2011
Scope binding
          function scopeBinding(){
            this.elem = {}

                function addMemberToElem(){
                   this.elem.newProperty = 5; // fail
                };

                addMemberToElem();
          }




Tuesday, August 2, 2011
Scope binding
          function scopeBinding(){
            this.elem = {};

                function addMemberToElem(){
                   this.elem.newProperty = 5;
                };

                addMemberToElem.call(this);
          }




Tuesday, August 2, 2011
Scope binding
          function scopeBinding(){
            this.elem = {}

                function addMemberToElem(propertyValue){
                   this.elem.newProperty = propertyValue;
                };

                addMemberToElem.call(this, 5);
          }




Tuesday, August 2, 2011
Scope binding
          function scopeBinding(){
            this.elem = {}

                var addMemberToElem = function(propertyValue){
                  this.elem.newProperty = propertyValue;
                }.bind(this);

                addMemberToElem(5);
          }




Tuesday, August 2, 2011
“But why should I do OOP
                             with JavaScript?”

Tuesday, August 2, 2011
“But why should I do OOP
                             with JavaScript?”

Tuesday, August 2, 2011
?
Tuesday, August 2, 2011

Mais conteúdo relacionado

Mais procurados

Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
Mario Fusco
 

Mais procurados (20)

Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
Java tutorial
Java tutorialJava tutorial
Java tutorial
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
scala
scalascala
scala
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Why we cannot ignore Functional Programming
Why we cannot ignore Functional ProgrammingWhy we cannot ignore Functional Programming
Why we cannot ignore Functional Programming
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 

Destaque

Destaque (6)

De la validarea formularelor Web la porcii verzi (utilizarea automatelor in c...
De la validarea formularelor Web la porcii verzi (utilizarea automatelor in c...De la validarea formularelor Web la porcii verzi (utilizarea automatelor in c...
De la validarea formularelor Web la porcii verzi (utilizarea automatelor in c...
 
[TW] Node.js
[TW] Node.js[TW] Node.js
[TW] Node.js
 
Pagini web mai rapide
Pagini web mai rapidePagini web mai rapide
Pagini web mai rapide
 
Frontline 2.3
Frontline 2.3Frontline 2.3
Frontline 2.3
 
Alec Williams - Author Allies, Poet Partners and Story Stars: Working with Cr...
Alec Williams - Author Allies, Poet Partners and Story Stars: Working with Cr...Alec Williams - Author Allies, Poet Partners and Story Stars: Working with Cr...
Alec Williams - Author Allies, Poet Partners and Story Stars: Working with Cr...
 
JPSSE - Partido State University
JPSSE - Partido State UniversityJPSSE - Partido State University
JPSSE - Partido State University
 

Semelhante a Javascript, Do you speak it!

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
OpenBlend society
 

Semelhante a Javascript, Do you speak it! (20)

Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Programming with Freedom & Joy
Programming with Freedom & JoyProgramming with Freedom & Joy
Programming with Freedom & Joy
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
oojs
oojsoojs
oojs
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
JavsScript OOP
JavsScript OOPJavsScript OOP
JavsScript OOP
 
Java
JavaJava
Java
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
 
JavaSE 7
JavaSE 7JavaSE 7
JavaSE 7
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
 

Mais de Victor Porof

Mais de Victor Porof (11)

Firefox WebGL developer tools
Firefox WebGL developer toolsFirefox WebGL developer tools
Firefox WebGL developer tools
 
Firefox developer tools
Firefox developer toolsFirefox developer tools
Firefox developer tools
 
Js in the open
Js in the openJs in the open
Js in the open
 
Processing.js vs. three.js
Processing.js vs. three.jsProcessing.js vs. three.js
Processing.js vs. three.js
 
Cityquest - Developing games for the mobile devices
Cityquest - Developing games for the mobile devicesCityquest - Developing games for the mobile devices
Cityquest - Developing games for the mobile devices
 
Web3D - Semantic standards, WebGL, HCI
Web3D - Semantic standards, WebGL, HCIWeb3D - Semantic standards, WebGL, HCI
Web3D - Semantic standards, WebGL, HCI
 
Chameleon game engine
Chameleon game engineChameleon game engine
Chameleon game engine
 
Developing web apps using Java and the Play framework
Developing web apps using Java and the Play frameworkDeveloping web apps using Java and the Play framework
Developing web apps using Java and the Play framework
 
Beginners' guide to Ruby on Rails
Beginners' guide to Ruby on RailsBeginners' guide to Ruby on Rails
Beginners' guide to Ruby on Rails
 
Introduction to the XNA framework
Introduction to the XNA frameworkIntroduction to the XNA framework
Introduction to the XNA framework
 
Introduction to 3D and shaders
Introduction to 3D and shadersIntroduction to 3D and shaders
Introduction to 3D and shaders
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Javascript, Do you speak it!

  • 1. JavaScript Do you speak it! Tuesday, August 2, 2011
  • 2. !"#$%&'(&'&)* * +,&-*.%/012%*3%*4&5#663* 78(9::;#%7/<=$&>:"#$%&'(&'&)* Tuesday, August 2, 2011
  • 3. “The world’s most misunderstood programming language” Tuesday, August 2, 2011
  • 4. We’ll talk about why JavaScript is the most misunderstood programming language Object Oriented Programming in JavaScript function scope, closures, circular references making the web a little faster Tuesday, August 2, 2011
  • 5. JavaScript aka Mocha aka LiveScript aka JScript aka ECMAScript Tuesday, August 2, 2011
  • 6. Java... Script? somehow related to Java? maybe a subset? less capable interpreted version of Java? Tuesday, August 2, 2011
  • 7. Java... Script? developed by Netscape in 1997 (vs. 3.0 in 1999) Java prefix intended to create confusion JavaScript is not interpreted Java Tuesday, August 2, 2011
  • 8. Design errors 1 + “1” = ? 1 + +”1” = ? overloading “+” means both addition and string concatenation with type conversion error-prone “with” statement reserved word policies are much too strict semicolon insertion was “a huge mistake” Tuesday, August 2, 2011
  • 9. Bad implementations earlier implementations were buggy embedded horribly in browsers did not respect the ECMA standard Tuesday, August 2, 2011
  • 10. Evolution first versions of JavaScript were quite weak no exception handling, inner functions in its present form, it’s a full OOP language ECMAScript 5.1 Tuesday, August 2, 2011
  • 11. Overview types and operators, core objects, methods does not have classes, but this functionality is accomplished with object prototypes functions are objects (and can be passed around as parameters) Tuesday, August 2, 2011
  • 12. (Loosely) Types typeof Number instanceof String Boolean Object (Function, Array, Date, RegExp) Null Undefined Tuesday, August 2, 2011
  • 13. Lisp in C’s clothing C-like syntax (curly braces, for statement...) appears to be a procedural language it’s actually a functional language! Tuesday, August 2, 2011
  • 14. Haskell vs. JS palindr :: [Int] -> Bool palindr [] = True palindr [x] = True palindr xs = (head xs == last xs) && palindr (tail (init xs)) function palindr(xs) { var i, len = xs.length; for (i = 0; i < len / 2; i++) if (xs[i] !== xs[len - i - 1]) return false; return true; } Tuesday, August 2, 2011
  • 15. Objects JavaScript is fundamentally about objects usually implemented as hashtables objects are created using constructors use a namespace for them (don’t modify objects you don’t own) use JS sugar: var obj = {}; and var arr = []; Tuesday, August 2, 2011
  • 16. OOP class Dog { public string name = “”; public int yearsOld = 0; polymorphism void bark(int times); void bark(float volume); encapsulation void sleep(); } inheritance class Pudel : Dog { public int cuteness = 5; abstractization } Dog pinky = new Dog(); Dog leyla = new Pudel(); Tuesday, August 2, 2011
  • 17. Objects in JavaScript MyNamespace.Dog = function(){ this.name = “”; this.yearsOld = 0; }; MyNamespace.Dog.prototype = { bark: function(param){ }, sleep: function(){ } }; var pinky = new Dog(); var leyla = new Dog(); leyla.cuteness = 5; Tuesday, August 2, 2011
  • 18. Objects in JavaScript MyNamespace.Dog = function(){ this.name = “”; this.yearsOld = 0; }; no private members? MyNamespace.Dog.prototype = { bark: function(param){ }, sleep: function(){ } }; var pinky = new Dog(); var leyla = new Dog(); leyla.cuteness = 5; Tuesday, August 2, 2011
  • 19. Closures function foo(a, b){ function bar() { return a + b; } return bar(); var res1 = foo(5, 2); } var res2 = foo2(5, 2); function foo2(a, b){ var res3 = res2(3); function bar(c) { return a + b + c; } return bar; } Tuesday, August 2, 2011
  • 20. Private members MyNamespace.Dog = function(){ var name = “”; var yearsOld = 0; this.bark = function(param){ if (“Number” === typeof param) { } else { } }; this.sleep = function(){ }; }; var pinky = new Dog(); Tuesday, August 2, 2011
  • 21. Private members MyNamespace.Dog = function(paramName, paramYearsOld){ var name = paramName; var yearsOld = paramYearsOld; this.bark = function(param){ }; this.sleep = function(){ }; get nrYearsOld(){ return yearsOld; }; }; var pinky = new Dog(); console.log(pinky.nrYearsOld); Tuesday, August 2, 2011
  • 22. Why is JavaScript slow? Bad compilation? Tuesday, August 2, 2011
  • 23. Why is JavaScript slow? No compilation!* Tuesday, August 2, 2011
  • 24. Why is JavaScript slow? No compilation!* *yes, interpreters are a lot smarter these days, but.. Tuesday, August 2, 2011
  • 25. Scope chains function scope1(){ var elem2; function scope2(){ var elem2; function scope3(){ var elem3; var func = window.alert; return { something: elem4, somethingElse: elem5 } } } } Tuesday, August 2, 2011
  • 26. Memory leaks function leakMemory(){ var elem = somethingThatOccupiesLotsOfMemory; function inner(){ }; return inner; } var res1 = leakMemory(); var res2 = leakMemory(); Tuesday, August 2, 2011
  • 27. Circular references function leakMemory(){ var elem = document.getElementById(“someId”); elem.onclick = function(){ }; } Tuesday, August 2, 2011
  • 28. Circular references function dontLeakMemory(){ var elem = document.getElementById(“someId”); elem.onclick = function(){ }; elem = null; } Tuesday, August 2, 2011
  • 29. Circular references function leakMemory(){ var elem = document.getElementById(“someId”); elem.onclick = function(){ }; return elem; } Tuesday, August 2, 2011
  • 30. Circular references function dontLeakMemory(){ var elem = document.getElementById(“someId”); elem.onclick = function(){ }; try { return elem; } finally { elem = null; } } Tuesday, August 2, 2011
  • 31. Scope binding function scopeBinding(){ this.elem = {} function addMemberToElem(){ this.elem.newProperty = 5; // fail }; addMemberToElem(); } Tuesday, August 2, 2011
  • 32. Scope binding function scopeBinding(){ this.elem = {}; function addMemberToElem(){ this.elem.newProperty = 5; }; addMemberToElem.call(this); } Tuesday, August 2, 2011
  • 33. Scope binding function scopeBinding(){ this.elem = {} function addMemberToElem(propertyValue){ this.elem.newProperty = propertyValue; }; addMemberToElem.call(this, 5); } Tuesday, August 2, 2011
  • 34. Scope binding function scopeBinding(){ this.elem = {} var addMemberToElem = function(propertyValue){ this.elem.newProperty = propertyValue; }.bind(this); addMemberToElem(5); } Tuesday, August 2, 2011
  • 35. “But why should I do OOP with JavaScript?” Tuesday, August 2, 2011
  • 36. “But why should I do OOP with JavaScript?” Tuesday, August 2, 2011