SlideShare une entreprise Scribd logo
1  sur  48
presentation.call(this,
‘Advanced JavaScript Techniques’);
part = ‘I’;
Luis Atencio
Technical Readiness and Enablement
© 2014 Citrix. Confidential.2
General Purpose
Programming Language
Interpreted
Single Threaded
Functional
Non-classical inheritance
Web
Maintained by ECMA Group
JavaScript is…
© 2014 Citrix. Confidential.3
JavaScript today
• Language of the Year 2014!
• Frameworks
• Backbone.js
• JavaScriptMVC
• *.JS
• Platforms
• AngularJS
• Future ECMA Proposals
• Node.JS -> Chrome V8 Engine
© 2014 Citrix. Confidential.4
“”
“JavaScript is a misunderstood language”
Douglas Crockford
PayPal
© 2014 Citrix. Confidential.5
OBJECTS CLOSURES
FUNCTIONS
To become a JavaScript expert you need to understand
“Everything is an Object”
Objects and Inheritance
© 2014 Citrix. Confidential.7
Object instantiation
function Person(first, last) {
var _firstname = first
var _lastname = last
this.getFullName = function () {
return [_firstname, _lastname].join(“ ”);
}
}
var p = new Person();
var Person = {first: ‘Luis’, last: ‘Atencio’};
var p = Object.create(Person);
instanceof checks work on
both scenarios
This is the prototype
© 2014 Citrix. Confidential.8
Prototype
• A prototype is an object from which other objects inherit properties
• Prototype is a special property of the constructor function, not of the instance.
• A constructor creates objects. Each constructor has an associated prototype
object, which is simply another object.
• When an object is created, it’s parent is set to the prototype object associated
with the constructor that created it
Content borrowed from Bala’s presentation
© 2014 Citrix. Confidential.9
Dissecting an Object
person Object
person
[[Prototype]]
Object
constructor
hasOwnProperty
isPrototypeOf
propertyIsEnumerable
toLocaleString
toString
valueOf
[[Prototype]]
the __proto__ property
the prototype object
null
var person = {};
Content borrowed from Bala’s presentation
© 2014 Citrix. Confidential.10
Constructors
Content borrowed from Bala’s presentation
When a function is called with the new operator, the function serves as the constructor for that class.
Internally, JavaScript creates an object, and then calls the constructor function. Inside the
constructor, the variable this is initialized to point to the just created Object.
obj = new Object;
obj.x = 1;
obj.y = 2;
function Foo() {
this.x = 1;
this.y = 2;
}
var obj = new Foo();
© 2014 Citrix. Confidential.11
Prototype vs __proto__
© 2014 Citrix. Confidential.12
var bob = Person('Bob');
bob instanceof Person //false
FORGETTING
TO CALL new
© 2014 Citrix. Confidential.13
instance
prototype constructor.prototype
Superclass…
Undefined
constructor.prototype
var obj = new Object();
alert (obj.toString());
Object
© 2014 Citrix. Confidential.14
Subclass.prototype = new SuperClass();
© 2014 Citrix. Confidential.15
instanceof VS typeof
• Typeof is a unary operator
• Good for telling apart the basic type of object: number, string, object, function…
• typeof null === ‘object’
• typeof [] === ‘object’
• Instanceof is a binary operator
• Inspects prototype chain
• Use to tell the type of object an instance belongs to
• p instanceof Person
• p instanceof Object
© 2014 Citrix. Confidential.16
Coercion
var Twelve = new Number(12);
var fifteen = Twelve + 3;
fifteen; //15
typeof fifteen; //"number" (primitive)
typeof Twelve; //"object"; (still object)
object coerced to primitive
© 2014 Citrix. Confidential.17
Keep in mind…
• Do not try to extend native objects: Number, Array, etc
• Affects Globally
• Not forward compatible
• One example: forEach (introduced in ECMAScript 5.1)
• Rather than extending native classes (like Array), try creating array-like classes
Functions
© 2014 Citrix. Confidential.19
Parameter Passing
• Objects pass by reference
• Arrays
• Objects
• null
• Primitives pass by value
• Strings
• Numbers
© 2014 Citrix. Confidential.20
JavaScript Functions
• JS unit of abstraction and behavior
• First-class objects ≈ a value ≈ an object
• Callable - Invoked via the ( ) operator
• Used to create object instances
• Have 2 important properties:
• name: the name of the function
• length: the number of formal arguments
• arguments: an array-like structure that contains the function arguments
© 2014 Citrix. Confidential.21
JavaScript Functions as First-Class Objects
var someFunc = function () { return ”ABC"}; // assigned to a variable
someFunc();
function someFunc() { // created with name
return "ABC”;
};
(function () { // Immediately-Invoked function expression (IIFE)
// module content here
})();
© 2014 Citrix. Confidential.22
JavaScript Functions as First Class objects2
function someFunc(otherFunc) { // as argument to function
var innerResult = otherFunc();
return innerResult;
};
function someFunc() { // returned from functions
return function () {
return “ABC”;
}
};
Closures
© 2014 Citrix. Confidential.24
Function’s Closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
Function declaration “closes
over” all variables (local and
global) present at the moment
of function declaration
“x” is part stored in the
function’s stack
© 2014 Citrix. Confidential.25
Emulating Private Methods
var counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
}
};
})();
Immediately Invoked Function
Execution IIFE
privateCounter is only visible
within the scope of the
function
© 2014 Citrix. Confidential.26
Duck Typing
function myArray() { }
MyArray.prototype.length = 0;
(function() {
var methods = [‘push’, ‘pop’, ‘slice’, ‘join’];
for(var i = 0; i < methods.length; i++)(function(name) {
MyArray.prototype[name] = function() {
return Array.prototype[name].apply(this, arguments);
};
})(methods[i]);
})();
var myObj = new MyArray();
myObj.push(1,2,3);
Scope
© 2014 Citrix. Confidential.28
Function Level Scope
• Scope changes inside functions
• This is JavaScript’s main scoping rule
• Variables declared are LOCAL to the
function in which they are declared
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
© 2014 Citrix. Confidential.29
Global Scope
• Declared outside the context of a
function
• All functions and modules have access
to this data
• Should be used with caution!
• Variables without var are automatically
global. Not allowed in strict mode.
var carName = ”Z";
function myFunction() {
carMake = “Nissan”;
// code everywhere can use carName and
carMake
}
© 2014 Citrix. Confidential.30
Block Scope
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
JavaScript does not use
block-level scope. Through a
process called “hoisting”
declarations are defined at
the top of the enclosing
function, assignment is
defined at the moment the
assignment is made
Prints out the value “10”
© 2014 Citrix. Confidential.31
Block Scope2
- More Hoisting
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Prints out the value “1” !!!
Function declaration is
hoisted to the top of the
function, overriding the value
for a entirely
Minimum vertical distance
principle
© 2014 Citrix. Confidential.32
Block Scope3
- Let
if (x > y) {
let gamma = 12.7 + y;
i = gamma * x;
}
gamma only exists in the context
of this block
© 2014 Citrix. Confidential.33
Remember with?
© 2014 Citrix. Confidential.34
BAD
PRACTICE
var someFunc = function () { return "ABC"};
var myObj = {
someProp = 4,
someFunc = function () { return "XYZ"};
};
with (myObj) {
// bound the scope of myObj into the curly
braces
var xyz= someFunc(); // confusing???
alert (xyz); // prints XYZ
}
Enterprise-class JavaScript Applications
© 2014 Citrix. Confidential.36
AngularJS
• Open Source web application framework maintained
by Google
• Client side MVC
• Web Components
• Declarative Programming platform
• Pre-Process HTML page and interpreting custom
HTML attributes that can then be manipulated via
JavaScript.
© 2014 Citrix. Confidential.37
Great JS Libraries
• Writing Object Oriented JS
• Prototype.js
• Backbone.js
• Ember.js
• Writing Cross-Browser JS
• JQuery.js
• Unit testing JS
• JSUnit
• QUnit
New Language Features
© 2014 Citrix. Confidential.39
Strict Mode
• Opt in to a restricted variant of JavaScript
• Eliminate silent errors by changing them to throw
• Makes it easier for JS engine optimizations
• Prohibits syntax to be defined in future versions
• Different semantics from normal mode
• Both modes can coexist
ECMAScript 5
(function(){
"use strict";
var foo = "test";
console.log(test);
})();
© 2014 Citrix. Confidential.40
Getters and Setters
ECMAScript 5
var obj = {
get foo() {
return 'getter';
},
set foo(value) {
console.log('setter: ’ + value);
}
};
obj.foo = ’bar'; // setter: bar
obj.foo // 'getter'
© 2014 Citrix. Confidential.41
Arrow Functions (lambdas)
Implement the … operator.
Syntax:
() => { };
Java 8 recently introduced this
let x = [0,1,2];
x.map(x => console.log(x * x));
ECMAScript 6
© 2014 Citrix. Confidential.42
Variadic Functions
Implement the … operator.
Syntax:
function* name(
[param[, param[, ... param]]]) {
statements
}
ECMAScript 6
© 2014 Citrix. Confidential.43
Array Comprehension
Very popular in Python and
Perl
Shorten operations on multiple
items
Format:
[for (x of iterable)
if (condition) x]
// simple example
var abc = [“A”, “B”, “C”];
[for (letters in abc) letters.lowerCase()]
// another example (with if)
var years = [1954, 1974, 1990, 2006, 2010];
[for (year of years) if (year > 2000) year];
ECMAScript 7
next.call(this,
‘Advanced JavaScript Techniques’);
part = ‘II’;
© 2014 Citrix. Confidential.45
Covers
•Functions Invocation
•Dynamic Scoping
•Functional Programming
• Why?
• Benefits
• Techniques
Resources
© 2014 Citrix. Confidential.47
Great Resources
• http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/
• Resig, John and Bibeault, Bear. Secrets of a JavaScript Ninja. Manning Publications
• http://javascript.crockford.com/javascript.html
• http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
• http://dmitrysoshnikov.com/ecmascript/javascript-the-core/
• http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/
© 2014 Citrix. Confidential.48
WORK BETTER. LIVE BETTER.

Contenu connexe

Tendances

Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
Ran Mizrahi
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
Dinh Pham
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 

Tendances (20)

Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtime
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: Concurrency
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
Node.js code tracing
Node.js code tracingNode.js code tracing
Node.js code tracing
 
Asynchronous Functions In C++
Asynchronous Functions In C++Asynchronous Functions In C++
Asynchronous Functions In C++
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Serving QML applications over the network
Serving QML applications over the networkServing QML applications over the network
Serving QML applications over the network
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
One Year of Clean Architecture - The Good, The Bad and The Bob
One Year of Clean Architecture - The Good, The Bad and The BobOne Year of Clean Architecture - The Good, The Bad and The Bob
One Year of Clean Architecture - The Good, The Bad and The Bob
 

Similaire à Java script Techniques Part I

JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
aragozin
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 

Similaire à Java script Techniques Part I (20)

JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to Griffon
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline Execution
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
oojs
oojsoojs
oojs
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 

Plus de Luis Atencio

379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 

Plus de Luis Atencio (8)

Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced Beginner
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
 
DZone_RC_RxJS
DZone_RC_RxJSDZone_RC_RxJS
DZone_RC_RxJS
 
PHP = PHunctional Programming
PHP = PHunctional ProgrammingPHP = PHunctional Programming
PHP = PHunctional Programming
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Luis atencio on_git
Luis atencio on_gitLuis atencio on_git
Luis atencio on_git
 

Dernier

%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Dernier (20)

OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Java script Techniques Part I

  • 1. presentation.call(this, ‘Advanced JavaScript Techniques’); part = ‘I’; Luis Atencio Technical Readiness and Enablement
  • 2. © 2014 Citrix. Confidential.2 General Purpose Programming Language Interpreted Single Threaded Functional Non-classical inheritance Web Maintained by ECMA Group JavaScript is…
  • 3. © 2014 Citrix. Confidential.3 JavaScript today • Language of the Year 2014! • Frameworks • Backbone.js • JavaScriptMVC • *.JS • Platforms • AngularJS • Future ECMA Proposals • Node.JS -> Chrome V8 Engine
  • 4. © 2014 Citrix. Confidential.4 “” “JavaScript is a misunderstood language” Douglas Crockford PayPal
  • 5. © 2014 Citrix. Confidential.5 OBJECTS CLOSURES FUNCTIONS To become a JavaScript expert you need to understand
  • 6. “Everything is an Object” Objects and Inheritance
  • 7. © 2014 Citrix. Confidential.7 Object instantiation function Person(first, last) { var _firstname = first var _lastname = last this.getFullName = function () { return [_firstname, _lastname].join(“ ”); } } var p = new Person(); var Person = {first: ‘Luis’, last: ‘Atencio’}; var p = Object.create(Person); instanceof checks work on both scenarios This is the prototype
  • 8. © 2014 Citrix. Confidential.8 Prototype • A prototype is an object from which other objects inherit properties • Prototype is a special property of the constructor function, not of the instance. • A constructor creates objects. Each constructor has an associated prototype object, which is simply another object. • When an object is created, it’s parent is set to the prototype object associated with the constructor that created it Content borrowed from Bala’s presentation
  • 9. © 2014 Citrix. Confidential.9 Dissecting an Object person Object person [[Prototype]] Object constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf [[Prototype]] the __proto__ property the prototype object null var person = {}; Content borrowed from Bala’s presentation
  • 10. © 2014 Citrix. Confidential.10 Constructors Content borrowed from Bala’s presentation When a function is called with the new operator, the function serves as the constructor for that class. Internally, JavaScript creates an object, and then calls the constructor function. Inside the constructor, the variable this is initialized to point to the just created Object. obj = new Object; obj.x = 1; obj.y = 2; function Foo() { this.x = 1; this.y = 2; } var obj = new Foo();
  • 11. © 2014 Citrix. Confidential.11 Prototype vs __proto__
  • 12. © 2014 Citrix. Confidential.12 var bob = Person('Bob'); bob instanceof Person //false FORGETTING TO CALL new
  • 13. © 2014 Citrix. Confidential.13 instance prototype constructor.prototype Superclass… Undefined constructor.prototype var obj = new Object(); alert (obj.toString()); Object
  • 14. © 2014 Citrix. Confidential.14 Subclass.prototype = new SuperClass();
  • 15. © 2014 Citrix. Confidential.15 instanceof VS typeof • Typeof is a unary operator • Good for telling apart the basic type of object: number, string, object, function… • typeof null === ‘object’ • typeof [] === ‘object’ • Instanceof is a binary operator • Inspects prototype chain • Use to tell the type of object an instance belongs to • p instanceof Person • p instanceof Object
  • 16. © 2014 Citrix. Confidential.16 Coercion var Twelve = new Number(12); var fifteen = Twelve + 3; fifteen; //15 typeof fifteen; //"number" (primitive) typeof Twelve; //"object"; (still object) object coerced to primitive
  • 17. © 2014 Citrix. Confidential.17 Keep in mind… • Do not try to extend native objects: Number, Array, etc • Affects Globally • Not forward compatible • One example: forEach (introduced in ECMAScript 5.1) • Rather than extending native classes (like Array), try creating array-like classes
  • 19. © 2014 Citrix. Confidential.19 Parameter Passing • Objects pass by reference • Arrays • Objects • null • Primitives pass by value • Strings • Numbers
  • 20. © 2014 Citrix. Confidential.20 JavaScript Functions • JS unit of abstraction and behavior • First-class objects ≈ a value ≈ an object • Callable - Invoked via the ( ) operator • Used to create object instances • Have 2 important properties: • name: the name of the function • length: the number of formal arguments • arguments: an array-like structure that contains the function arguments
  • 21. © 2014 Citrix. Confidential.21 JavaScript Functions as First-Class Objects var someFunc = function () { return ”ABC"}; // assigned to a variable someFunc(); function someFunc() { // created with name return "ABC”; }; (function () { // Immediately-Invoked function expression (IIFE) // module content here })();
  • 22. © 2014 Citrix. Confidential.22 JavaScript Functions as First Class objects2 function someFunc(otherFunc) { // as argument to function var innerResult = otherFunc(); return innerResult; }; function someFunc() { // returned from functions return function () { return “ABC”; } };
  • 24. © 2014 Citrix. Confidential.24 Function’s Closure function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 Function declaration “closes over” all variables (local and global) present at the moment of function declaration “x” is part stored in the function’s stack
  • 25. © 2014 Citrix. Confidential.25 Emulating Private Methods var counter = (function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); } }; })(); Immediately Invoked Function Execution IIFE privateCounter is only visible within the scope of the function
  • 26. © 2014 Citrix. Confidential.26 Duck Typing function myArray() { } MyArray.prototype.length = 0; (function() { var methods = [‘push’, ‘pop’, ‘slice’, ‘join’]; for(var i = 0; i < methods.length; i++)(function(name) { MyArray.prototype[name] = function() { return Array.prototype[name].apply(this, arguments); }; })(methods[i]); })(); var myObj = new MyArray(); myObj.push(1,2,3);
  • 27. Scope
  • 28. © 2014 Citrix. Confidential.28 Function Level Scope • Scope changes inside functions • This is JavaScript’s main scoping rule • Variables declared are LOCAL to the function in which they are declared function myFunction() { var carName = "Volvo"; // code here can use carName }
  • 29. © 2014 Citrix. Confidential.29 Global Scope • Declared outside the context of a function • All functions and modules have access to this data • Should be used with caution! • Variables without var are automatically global. Not allowed in strict mode. var carName = ”Z"; function myFunction() { carMake = “Nissan”; // code everywhere can use carName and carMake }
  • 30. © 2014 Citrix. Confidential.30 Block Scope var foo = 1; function bar() { if (!foo) { var foo = 10; } alert(foo); } bar(); JavaScript does not use block-level scope. Through a process called “hoisting” declarations are defined at the top of the enclosing function, assignment is defined at the moment the assignment is made Prints out the value “10”
  • 31. © 2014 Citrix. Confidential.31 Block Scope2 - More Hoisting var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); Prints out the value “1” !!! Function declaration is hoisted to the top of the function, overriding the value for a entirely Minimum vertical distance principle
  • 32. © 2014 Citrix. Confidential.32 Block Scope3 - Let if (x > y) { let gamma = 12.7 + y; i = gamma * x; } gamma only exists in the context of this block
  • 33. © 2014 Citrix. Confidential.33 Remember with?
  • 34. © 2014 Citrix. Confidential.34 BAD PRACTICE var someFunc = function () { return "ABC"}; var myObj = { someProp = 4, someFunc = function () { return "XYZ"}; }; with (myObj) { // bound the scope of myObj into the curly braces var xyz= someFunc(); // confusing??? alert (xyz); // prints XYZ }
  • 36. © 2014 Citrix. Confidential.36 AngularJS • Open Source web application framework maintained by Google • Client side MVC • Web Components • Declarative Programming platform • Pre-Process HTML page and interpreting custom HTML attributes that can then be manipulated via JavaScript.
  • 37. © 2014 Citrix. Confidential.37 Great JS Libraries • Writing Object Oriented JS • Prototype.js • Backbone.js • Ember.js • Writing Cross-Browser JS • JQuery.js • Unit testing JS • JSUnit • QUnit
  • 39. © 2014 Citrix. Confidential.39 Strict Mode • Opt in to a restricted variant of JavaScript • Eliminate silent errors by changing them to throw • Makes it easier for JS engine optimizations • Prohibits syntax to be defined in future versions • Different semantics from normal mode • Both modes can coexist ECMAScript 5 (function(){ "use strict"; var foo = "test"; console.log(test); })();
  • 40. © 2014 Citrix. Confidential.40 Getters and Setters ECMAScript 5 var obj = { get foo() { return 'getter'; }, set foo(value) { console.log('setter: ’ + value); } }; obj.foo = ’bar'; // setter: bar obj.foo // 'getter'
  • 41. © 2014 Citrix. Confidential.41 Arrow Functions (lambdas) Implement the … operator. Syntax: () => { }; Java 8 recently introduced this let x = [0,1,2]; x.map(x => console.log(x * x)); ECMAScript 6
  • 42. © 2014 Citrix. Confidential.42 Variadic Functions Implement the … operator. Syntax: function* name( [param[, param[, ... param]]]) { statements } ECMAScript 6
  • 43. © 2014 Citrix. Confidential.43 Array Comprehension Very popular in Python and Perl Shorten operations on multiple items Format: [for (x of iterable) if (condition) x] // simple example var abc = [“A”, “B”, “C”]; [for (letters in abc) letters.lowerCase()] // another example (with if) var years = [1954, 1974, 1990, 2006, 2010]; [for (year of years) if (year > 2000) year]; ECMAScript 7
  • 45. © 2014 Citrix. Confidential.45 Covers •Functions Invocation •Dynamic Scoping •Functional Programming • Why? • Benefits • Techniques
  • 47. © 2014 Citrix. Confidential.47 Great Resources • http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/ • Resig, John and Bibeault, Bear. Secrets of a JavaScript Ninja. Manning Publications • http://javascript.crockford.com/javascript.html • http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html • http://dmitrysoshnikov.com/ecmascript/javascript-the-core/ • http://skilldrick.co.uk/2011/09/understanding-typeof-instanceof-and-constructor-in-javascript/
  • 48. © 2014 Citrix. Confidential.48 WORK BETTER. LIVE BETTER.

Notes de l'éditeur

  1. JS was supposed to be Scheme for the web while at Netscape Ran out of time, then they wanted to be more Java like Guys wrote it in a week, basically
  2. In javascript, every object has a constructor property that refers to the constructor function that initializes the object. function MyConstructor() {} var obj = new MyConstructor(); console.log(obj.constructor == MyConstructor); // true When you declare a function: function Person() {} The interpreter creates the new function object from your declaration. Together with the function, it’s prototype property is created and populated. This prototype is an object with property constructor, which is set to the function itself. MyConstructor.prototype = { constructor: MyConstructor }
  3. A global variable ‘name’ will created in the global space
  4. Constructor : references the constructor function used to create this object
  5. Inside bar, !foo returns true because of var foo would hoist it to the top and set it to null