SlideShare uma empresa Scribd logo
1 de 68
Baixar para ler offline
Advanced JavaScript
                  From Novice To Ninja

Tuesday, September 18, 12
Agenda

                  JavaScript History

                  Language Overview

                  Arrays & Objects

                  Functions




Tuesday, September 18, 12
The World’s Most
                     Misunderstood
                     Programming Language


Tuesday, September 18, 12
History
             1995 Brendan Eich started
             developing a new language
             for Netscape Navigator 2.0

             Original name was
             LiveScript

             Announced on Dec 1995 as
             JavaScript

             1996 Microsoft responded
             with JScript



Tuesday, September 18, 12
JS Today
                  Used for Client side
                  development on
                  desktop and mobile

                  Used for Server side
                  development using
                  NodeJs

                  Embedded in
                  applications using
                  Rhino

Tuesday, September 18, 12
Language Overview

                  JavaScript is not a toy

                  JavaScript has nothing to do with Java

                  JavaScript is a powerful programming language
                  on its own




Tuesday, September 18, 12
JavaScript Key Ideas
                  Interpreter based (no compilation)

                  Loosely typed language

                  Objects are just hash tables

                  Prototypical inheritance model

                  Functions are regular objects (with a twist)

                  Arrays are regular objects (with a twist)


Tuesday, September 18, 12
JavaScript Core Types
                  Numbers

                  Strings

                  Booleans

                  null

                  undefined

                  Objects


Tuesday, September 18, 12
JavaScript Gotchas

                  var x = “3”;

                  var y = 5;

                  x + y == 8;

                  x + y == 35;

                  x + y === 35;



Tuesday, September 18, 12
JavaScript Gotchas

                  var x = “3”;

                  var y = 5;

                  x + y == 8;    // false

                  x + y == 35; // true

                  x + y === 35; // false



Tuesday, September 18, 12
JavaScript Gotchas
                  function foo() {   function bar() {

                      return             return { val : 3 }
                                     }
                      {
                                     var x = foo();
                          val : 3
                      }              var y = bar();
                  }
                                     x.val == y.val;




Tuesday, September 18, 12
JavaScript Gotchas
                  // returns undef   // returns object

                  function foo() {   function bar() {

                      return             return { val : 3 }
                                     }
                      {
                                     var x = foo();
                          val : 3
                      }              var y = bar();
                  }
                                     x.val == y.val; // error




Tuesday, September 18, 12
JavaScript Gotchas

                  1          === 1;

                  1/0        === 1/0;

                  Number(‘a’) === Number(‘a’);

                  ‘a‘        === “a”




Tuesday, September 18, 12
JavaScript Gotchas

                  1          === 1;               // true

                  1/0        === 1/0;            // true

                  Number(‘a’) === Number(‘a’);     // false

                  ‘a‘        === “a”              // true




Tuesday, September 18, 12
Q&A

                  JavaScript History

                  Language Overview

                  Arrays & Objects

                  Functions




Tuesday, September 18, 12
Objects

                  JS Objects are container for data

                  A data field in an object is a name-value pair

                  The name can be any string

                  The value can be anything except undefined




Tuesday, September 18, 12
Using Objects

                   name      Ynon Perek




                   website   http://www.ynonperek.com




Tuesday, September 18, 12
Using Objects

                  var myObject = {

                            name : “Ynon Perek”,

                            website : “http://www.ynonperek.com”

                     }




Tuesday, September 18, 12
Using Objects


             console.dir(myObject); // prints all the fields

             myObject.name        === “Ynon Perek”

             myObject[‘website’] === http://www.ynonperek.com




Tuesday, September 18, 12
Object Patterns


                  Object Literals vs. Object Ctor

                  Maker functions

                  Object Prototypes




Tuesday, September 18, 12
Object Literals vs. Ctor

                  Using object literals is the recommended way to
                  create objects

                  It is faster than calling new Object()

                  It is more predictable than calling new Object()

                  It is simpler




Tuesday, September 18, 12
Maker Functions


Tuesday, September 18, 12
Maker Functions
             function Person(name, age) {

                  var that = { name : name, age : age };

                  that.hello = function() {

                            console.log(“Hello, My name is ” + that.name)

                  };

                  return that;
             }




Tuesday, September 18, 12
Maker Functions

                  Using a maker function to create new objects
                  saves duplicate code

                  Use the “that” pattern against “new” pitfalls

                  Load your newly created object with functions




Tuesday, September 18, 12
Example

                  Implement a Quiz JavaScript system

                  Use “Question” class with four possible answers
                  and on correct answer

                  Use “Quiz” class to hold an array of questions




Tuesday, September 18, 12
Object Prototypes




Tuesday, September 18, 12
Object Prototypes

                  In JavaScript, every object has a “prototype”
                  object.

                  When JS interpreter fails to find an attribute in an
                  object, it searches the prototype.




Tuesday, September 18, 12
Prototype Chain

         Freshman                         Student                Person
         goto: party                     grade : 90              age : 12




     Freshman.grade         ===   90     //   from   Student
     Student.age            ===   12     //   from   Person
     Worker.age             ===   12     //   from   Person       Worker
     Worker.salary          ===   3800   //   from   Worker    salary : 3800




Tuesday, September 18, 12
The object Function

             function object(parent) {
                     function F() {};

                            F.prototype = parent || Object;

                            return new F();

             }




Tuesday, September 18, 12
The object Function


                  creates a new object with the prototype ‘parent’

                  uses new to keep the prototype link

                  supports no arguments for object literals




Tuesday, September 18, 12
Prototype Example
             var person     = { age : 12 };

             var student     = object(person);

             student.grade = 90;



             var freshman   = object(student);

             freshman.goto = “party”;




Tuesday, September 18, 12
Prototypes & Makers


                  Always use Maker functions

                  For leafs, initialize object literals

                  For nodes, use the object() function




Tuesday, September 18, 12
Exercise
                  Write a maker function for a Car object, using an
                  object literal. Car should provide members:
                  max_speed and drive()

                  Write maker functions for 3 car models using the
                  object() function.

                  Implement a function on a car model which uses
                  data from Car



Tuesday, September 18, 12
Arrays


                  Arrays are objects with numeric keys.

                  A length attribute is maintained automatically by
                  JS to mean last_index + 1




Tuesday, September 18, 12
Array Functions
                  join

                  pop, push

                  shift, unshift

                  reverse, sort - changes original array

                  a.slice(0, a.length).reverse() - Does not modify
                  original array a



Tuesday, September 18, 12
Exercise

                  Implement a Phonebook object that maintains an
                  array of Contact objects.

                  Each Contact should have a name field and a
                  phone field.

                  Test by creating 5 contacts in the Phonebook and
                  print them to the console.




Tuesday, September 18, 12
Q&A

                  JavaScript History

                  Language Overview

                  Arrays & Objects

                  Functions




Tuesday, September 18, 12
Functions

                  The word ‘function’

                        Followed by an optional name

                        Followed by a set of parameters

                        Followed by the function body




Tuesday, September 18, 12
Functions
                  function hello(who) {
                   console.log(“Hello, “ + who);

                  }

                  var hello = function hello(who) {
                   console.log(“Hello, “ + who);

                  };




Tuesday, September 18, 12
Function.Prototype


                  apply, call

                  toString




Tuesday, September 18, 12
Scope


                  In JavaScript, only functions have scope.

                  The var keyword indicates a scoped variable

                  There is no block scope




Tuesday, September 18, 12
Scope
             // Using functions to scope our code

             (function() {
               var x = 5;

                  var y = 7;

                  console.log(x + y);

             }());




Tuesday, September 18, 12
Scope

                       Do:

                             Wrap every file in an anonymous function

                             Prefix every variable with var



                       A Good fence makes good neighbors



Tuesday, September 18, 12
Constructor Functions
                  If a function is called with new:

                        A new object is created before entering the
                        function

                        That object is passed as the this argument

                        That object becomes the default return value of
                        the function



Tuesday, September 18, 12
Return Value

                  return is used to return a value

                  default return value for non-ctor functions is
                  undefined

                  default return value for ctor is this




Tuesday, September 18, 12
Tip


                  Prefer that-style constructor over this

                  In that-style constructors, always remember to
                  return that.




Tuesday, September 18, 12
Function Patterns

                  Modules

                  Immediate Functions

                  Configuration Objects

                  Prototype Methods




Tuesday, September 18, 12
Modules

                  A module is a unit of code reuse

                  Some code in a module is “public” - shared with
                  other modules.

                  Some code in a module is “private” - cannot be
                  accessed from outside.




Tuesday, September 18, 12
Function Arguments
             function sum() {

                   var i = 0,

                            n = arguments.length,

                            sum = 0;




                   for ( i=0; i < n; ++i ) {

                            sum += arguments[i];

                   }




                   return sum;

             }




Tuesday, September 18, 12
Example - Calculator
                     Public code:

                            add_to_register

                            sub_from_register

                            read_register

                            zero_register

                     http://ynonperek.com/course/web/javascript-
                     functions.html#modules

Tuesday, September 18, 12
Immediate Functions

                  Execute a function as soon as it is defined

                  Provides a scoped “sandbox” for initialization
                  code

                  Pass in the global object to avoid using ‘window’
                  in your code.




Tuesday, September 18, 12
Configuration Objects

                  When a large list of arguments is required, use
                  configuration objects

                  Solves “which comes first”

                  Rule of Thumb: if params > 2, use the object




Tuesday, September 18, 12
Configuration Objects

                  Example

                        Student function which takes a configuration
                        object with optional values

                  http://ynonperek.com/course/web/javascript-
                  functions.html#conf




Tuesday, September 18, 12
Function Exercise

                  Write a module for time management

                  Module should provide:

                        add_meeting(meeting_info)

                        delete_meeting(meeting_info)

                        get_meetings_between(start_dt, end_dt)



Tuesday, September 18, 12
Function Patterns

                  Modules

                  Immediate Functions

                  Configuration Objects

                  Prototype Methods




Tuesday, September 18, 12
Function Prototypes




Tuesday, September 18, 12
Function Prototypes


                  functions have a special attribute: prototype

                  When an object’s attribute lookup is performed,
                  the interpreter checks its constructor.prototype




Tuesday, September 18, 12
Function Prototypes

                  We implement inheritance using prototypes - this
                  is called prototypical inheritance

                  Example: http://ynonperek.com/course/fed/
                  javascript-oo.html




Tuesday, September 18, 12
Design Patterns


                  Singleton

                  Factory

                  Super




Tuesday, September 18, 12
Singleton
                  Put the object on global.

                  Access it from everywhere in your program

                  Always consider using a namespace

                            global.Log = log;




Tuesday, September 18, 12
Factory
                  Use a single factory object with a method to
                  produce each product

                  Implement a product method that takes a name of
                  a product, and runs its correct producer function
                            CarFactory.produce = function(model) {
                              var ctor = CarFactory[model];
                              return ctor();
                            }




Tuesday, September 18, 12
Using Super

                  JavaScript has no native ‘super’ call

                  To use the superclass in the inheritance chain, we
                  must work something out ourselves

                  Let’s modify our object function to allow super




Tuesday, September 18, 12
Using Super

             function object(parent) {
                     function F() { /* CODE GOES HERE */ };

                            F.prototype = parent || Object;

                            return new F();

             }




Tuesday, September 18, 12
Using Super

             function object(parent) {
                     function F() { this.uber = parent };

                            F.prototype = parent || Object;

                            return new F();

             }




Tuesday, September 18, 12
Using Super


                  Now each object has an ‘uber’ property that
                  points to its prototype object

                  Can use student.uber.age to get the person’s age




Tuesday, September 18, 12
JS App Tips
                  App is made of components. On mobile, only one
                  visible component at a time; on Desktop, can have
                  more than one.

                  Each component has its own JS file

                  Different components can communicate using a
                  global object in a private namespace

                  A single controller object moves components in/
                  out of view


Tuesday, September 18, 12
Q&A
Tuesday, September 18, 12
Thank You


                  Ynon Perek

                  ynonperek@yahoo.com

                  ynonperek.com




Tuesday, September 18, 12

Mais conteúdo relacionado

Destaque

Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScriptYnon Perek
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
JavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesJavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesChicago ALT.NET
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScriptd0nn9n
 
General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptSpike Brehm
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesSencha
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIYnon Perek
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer ToolboxYnon Perek
 
Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming IntroYnon Perek
 

Destaque (19)

Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
JavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesJavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly Braces
 
Douglas - Real JavaScript
Douglas - Real JavaScriptDouglas - Real JavaScript
Douglas - Real JavaScript
 
General Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScriptGeneral Assembly Workshop: Advanced JavaScript
General Assembly Workshop: Advanced JavaScript
 
JavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other PuzzlesJavaScript: Advanced Scoping & Other Puzzles
JavaScript: Advanced Scoping & Other Puzzles
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Intro to SVGs
Intro to SVGsIntro to SVGs
Intro to SVGs
 
Css2
Css2Css2
Css2
 
Html5 apis
Html5 apisHtml5 apis
Html5 apis
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
 
Performance
PerformancePerformance
Performance
 
08 ajax
08 ajax08 ajax
08 ajax
 
Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming Intro
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 

Semelhante a 03 Advanced JavaScript

Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScriptnodejsbcn
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitTasanakorn Phaipool
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScriptJohn Hann
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.jsJay Phelps
 

Semelhante a 03 Advanced JavaScript (7)

Js in the open
Js in the openJs in the open
Js in the open
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
 
Metamoose
MetamooseMetamoose
Metamoose
 
JavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnitJavaScript Test-Driven Development (TDD) with QUnit
JavaScript Test-Driven Development (TDD) with QUnit
 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScript
 
Intro to Ember.js
Intro to Ember.jsIntro to Ember.js
Intro to Ember.js
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 

Mais de Ynon Perek

09 performance
09 performance09 performance
09 performanceYnon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web IntroYnon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile DevicesYnon Perek
 
Architecture app
Architecture appArchitecture app
Architecture appYnon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and RubyYnon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application TestingYnon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application SecurityYnon Perek
 

Mais de Ynon Perek (20)

Regexp
RegexpRegexp
Regexp
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 
09 performance
09 performance09 performance
09 performance
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Vimperl
VimperlVimperl
Vimperl
 
Syllabus
SyllabusSyllabus
Syllabus
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
 
Network
NetworkNetwork
Network
 
Architecture app
Architecture appArchitecture app
Architecture app
 
Cryptography
CryptographyCryptography
Cryptography
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
 
Accessibility
AccessibilityAccessibility
Accessibility
 
Angularjs
AngularjsAngularjs
Angularjs
 
Js memory
Js memoryJs memory
Js memory
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 

Último

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...BookNet Canada
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 

Último (20)

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
Transcript: New from BookNet Canada for 2024: BNC SalesData and LibraryData -...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 

03 Advanced JavaScript

  • 1. Advanced JavaScript From Novice To Ninja Tuesday, September 18, 12
  • 2. Agenda JavaScript History Language Overview Arrays & Objects Functions Tuesday, September 18, 12
  • 3. The World’s Most Misunderstood Programming Language Tuesday, September 18, 12
  • 4. History 1995 Brendan Eich started developing a new language for Netscape Navigator 2.0 Original name was LiveScript Announced on Dec 1995 as JavaScript 1996 Microsoft responded with JScript Tuesday, September 18, 12
  • 5. JS Today Used for Client side development on desktop and mobile Used for Server side development using NodeJs Embedded in applications using Rhino Tuesday, September 18, 12
  • 6. Language Overview JavaScript is not a toy JavaScript has nothing to do with Java JavaScript is a powerful programming language on its own Tuesday, September 18, 12
  • 7. JavaScript Key Ideas Interpreter based (no compilation) Loosely typed language Objects are just hash tables Prototypical inheritance model Functions are regular objects (with a twist) Arrays are regular objects (with a twist) Tuesday, September 18, 12
  • 8. JavaScript Core Types Numbers Strings Booleans null undefined Objects Tuesday, September 18, 12
  • 9. JavaScript Gotchas var x = “3”; var y = 5; x + y == 8; x + y == 35; x + y === 35; Tuesday, September 18, 12
  • 10. JavaScript Gotchas var x = “3”; var y = 5; x + y == 8; // false x + y == 35; // true x + y === 35; // false Tuesday, September 18, 12
  • 11. JavaScript Gotchas function foo() { function bar() { return return { val : 3 } } { var x = foo(); val : 3 } var y = bar(); } x.val == y.val; Tuesday, September 18, 12
  • 12. JavaScript Gotchas // returns undef // returns object function foo() { function bar() { return return { val : 3 } } { var x = foo(); val : 3 } var y = bar(); } x.val == y.val; // error Tuesday, September 18, 12
  • 13. JavaScript Gotchas 1 === 1; 1/0 === 1/0; Number(‘a’) === Number(‘a’); ‘a‘ === “a” Tuesday, September 18, 12
  • 14. JavaScript Gotchas 1 === 1; // true 1/0 === 1/0; // true Number(‘a’) === Number(‘a’); // false ‘a‘ === “a” // true Tuesday, September 18, 12
  • 15. Q&A JavaScript History Language Overview Arrays & Objects Functions Tuesday, September 18, 12
  • 16. Objects JS Objects are container for data A data field in an object is a name-value pair The name can be any string The value can be anything except undefined Tuesday, September 18, 12
  • 17. Using Objects name Ynon Perek website http://www.ynonperek.com Tuesday, September 18, 12
  • 18. Using Objects var myObject = { name : “Ynon Perek”, website : “http://www.ynonperek.com” } Tuesday, September 18, 12
  • 19. Using Objects console.dir(myObject); // prints all the fields myObject.name === “Ynon Perek” myObject[‘website’] === http://www.ynonperek.com Tuesday, September 18, 12
  • 20. Object Patterns Object Literals vs. Object Ctor Maker functions Object Prototypes Tuesday, September 18, 12
  • 21. Object Literals vs. Ctor Using object literals is the recommended way to create objects It is faster than calling new Object() It is more predictable than calling new Object() It is simpler Tuesday, September 18, 12
  • 23. Maker Functions function Person(name, age) { var that = { name : name, age : age }; that.hello = function() { console.log(“Hello, My name is ” + that.name) }; return that; } Tuesday, September 18, 12
  • 24. Maker Functions Using a maker function to create new objects saves duplicate code Use the “that” pattern against “new” pitfalls Load your newly created object with functions Tuesday, September 18, 12
  • 25. Example Implement a Quiz JavaScript system Use “Question” class with four possible answers and on correct answer Use “Quiz” class to hold an array of questions Tuesday, September 18, 12
  • 27. Object Prototypes In JavaScript, every object has a “prototype” object. When JS interpreter fails to find an attribute in an object, it searches the prototype. Tuesday, September 18, 12
  • 28. Prototype Chain Freshman Student Person goto: party grade : 90 age : 12 Freshman.grade === 90 // from Student Student.age === 12 // from Person Worker.age === 12 // from Person Worker Worker.salary === 3800 // from Worker salary : 3800 Tuesday, September 18, 12
  • 29. The object Function function object(parent) { function F() {}; F.prototype = parent || Object; return new F(); } Tuesday, September 18, 12
  • 30. The object Function creates a new object with the prototype ‘parent’ uses new to keep the prototype link supports no arguments for object literals Tuesday, September 18, 12
  • 31. Prototype Example var person = { age : 12 }; var student = object(person); student.grade = 90; var freshman = object(student); freshman.goto = “party”; Tuesday, September 18, 12
  • 32. Prototypes & Makers Always use Maker functions For leafs, initialize object literals For nodes, use the object() function Tuesday, September 18, 12
  • 33. Exercise Write a maker function for a Car object, using an object literal. Car should provide members: max_speed and drive() Write maker functions for 3 car models using the object() function. Implement a function on a car model which uses data from Car Tuesday, September 18, 12
  • 34. Arrays Arrays are objects with numeric keys. A length attribute is maintained automatically by JS to mean last_index + 1 Tuesday, September 18, 12
  • 35. Array Functions join pop, push shift, unshift reverse, sort - changes original array a.slice(0, a.length).reverse() - Does not modify original array a Tuesday, September 18, 12
  • 36. Exercise Implement a Phonebook object that maintains an array of Contact objects. Each Contact should have a name field and a phone field. Test by creating 5 contacts in the Phonebook and print them to the console. Tuesday, September 18, 12
  • 37. Q&A JavaScript History Language Overview Arrays & Objects Functions Tuesday, September 18, 12
  • 38. Functions The word ‘function’ Followed by an optional name Followed by a set of parameters Followed by the function body Tuesday, September 18, 12
  • 39. Functions function hello(who) { console.log(“Hello, “ + who); } var hello = function hello(who) { console.log(“Hello, “ + who); }; Tuesday, September 18, 12
  • 40. Function.Prototype apply, call toString Tuesday, September 18, 12
  • 41. Scope In JavaScript, only functions have scope. The var keyword indicates a scoped variable There is no block scope Tuesday, September 18, 12
  • 42. Scope // Using functions to scope our code (function() { var x = 5; var y = 7; console.log(x + y); }()); Tuesday, September 18, 12
  • 43. Scope Do: Wrap every file in an anonymous function Prefix every variable with var A Good fence makes good neighbors Tuesday, September 18, 12
  • 44. Constructor Functions If a function is called with new: A new object is created before entering the function That object is passed as the this argument That object becomes the default return value of the function Tuesday, September 18, 12
  • 45. Return Value return is used to return a value default return value for non-ctor functions is undefined default return value for ctor is this Tuesday, September 18, 12
  • 46. Tip Prefer that-style constructor over this In that-style constructors, always remember to return that. Tuesday, September 18, 12
  • 47. Function Patterns Modules Immediate Functions Configuration Objects Prototype Methods Tuesday, September 18, 12
  • 48. Modules A module is a unit of code reuse Some code in a module is “public” - shared with other modules. Some code in a module is “private” - cannot be accessed from outside. Tuesday, September 18, 12
  • 49. Function Arguments function sum() { var i = 0, n = arguments.length, sum = 0; for ( i=0; i < n; ++i ) { sum += arguments[i]; } return sum; } Tuesday, September 18, 12
  • 50. Example - Calculator Public code: add_to_register sub_from_register read_register zero_register http://ynonperek.com/course/web/javascript- functions.html#modules Tuesday, September 18, 12
  • 51. Immediate Functions Execute a function as soon as it is defined Provides a scoped “sandbox” for initialization code Pass in the global object to avoid using ‘window’ in your code. Tuesday, September 18, 12
  • 52. Configuration Objects When a large list of arguments is required, use configuration objects Solves “which comes first” Rule of Thumb: if params > 2, use the object Tuesday, September 18, 12
  • 53. Configuration Objects Example Student function which takes a configuration object with optional values http://ynonperek.com/course/web/javascript- functions.html#conf Tuesday, September 18, 12
  • 54. Function Exercise Write a module for time management Module should provide: add_meeting(meeting_info) delete_meeting(meeting_info) get_meetings_between(start_dt, end_dt) Tuesday, September 18, 12
  • 55. Function Patterns Modules Immediate Functions Configuration Objects Prototype Methods Tuesday, September 18, 12
  • 57. Function Prototypes functions have a special attribute: prototype When an object’s attribute lookup is performed, the interpreter checks its constructor.prototype Tuesday, September 18, 12
  • 58. Function Prototypes We implement inheritance using prototypes - this is called prototypical inheritance Example: http://ynonperek.com/course/fed/ javascript-oo.html Tuesday, September 18, 12
  • 59. Design Patterns Singleton Factory Super Tuesday, September 18, 12
  • 60. Singleton Put the object on global. Access it from everywhere in your program Always consider using a namespace global.Log = log; Tuesday, September 18, 12
  • 61. Factory Use a single factory object with a method to produce each product Implement a product method that takes a name of a product, and runs its correct producer function CarFactory.produce = function(model) { var ctor = CarFactory[model]; return ctor(); } Tuesday, September 18, 12
  • 62. Using Super JavaScript has no native ‘super’ call To use the superclass in the inheritance chain, we must work something out ourselves Let’s modify our object function to allow super Tuesday, September 18, 12
  • 63. Using Super function object(parent) { function F() { /* CODE GOES HERE */ }; F.prototype = parent || Object; return new F(); } Tuesday, September 18, 12
  • 64. Using Super function object(parent) { function F() { this.uber = parent }; F.prototype = parent || Object; return new F(); } Tuesday, September 18, 12
  • 65. Using Super Now each object has an ‘uber’ property that points to its prototype object Can use student.uber.age to get the person’s age Tuesday, September 18, 12
  • 66. JS App Tips App is made of components. On mobile, only one visible component at a time; on Desktop, can have more than one. Each component has its own JS file Different components can communicate using a global object in a private namespace A single controller object moves components in/ out of view Tuesday, September 18, 12
  • 68. Thank You Ynon Perek ynonperek@yahoo.com ynonperek.com Tuesday, September 18, 12