SlideShare uma empresa Scribd logo
1 de 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.

Mais conteúdo relacionado

Mais procurados

Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtimeInferis
 
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 DispatchMatteo Battaglio
 
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 IICS
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
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
 
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 IIIICS
 
Better Code: Concurrency
Better Code: ConcurrencyBetter Code: Concurrency
Better Code: ConcurrencyPlatonov Sergey
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
Asynchronous Functions In C++
Asynchronous Functions In C++Asynchronous Functions In C++
Asynchronous Functions In C++Schalk Cronjé
 
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 & UXJWORKS powered by Ordina
 
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
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Serving QML applications over the network
Serving QML applications over the networkServing QML applications over the network
Serving QML applications over the networkJeremy Lainé
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
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 BobOCTO Technology
 

Mais procurados (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
 

Semelhante a 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 UpDavid Padbury
 
Porting legacy apps to Griffon
Porting legacy apps to GriffonPorting legacy apps to Griffon
Porting legacy apps to GriffonJames Williams
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
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 gradleThierry Wasylczenko
 
Docker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionDocker & ECS: Secure Nearline Execution
Docker & ECS: Secure Nearline ExecutionBrennan Saeta
 
Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvmaragozin
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java DevelopersYakov Fain
 
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...GITS Indonesia
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
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
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptYakov Fain
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 

Semelhante a 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
 

Mais de Luis Atencio

Functional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerFunctional programming for the Advanced Beginner
Functional programming for the Advanced BeginnerLuis Atencio
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogrammingLuis Atencio
 
PHP = PHunctional Programming
PHP = PHunctional ProgrammingPHP = PHunctional Programming
PHP = PHunctional ProgrammingLuis Atencio
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
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 AtencioLuis Atencio
 
Luis atencio on_git
Luis atencio on_gitLuis atencio on_git
Luis atencio on_gitLuis Atencio
 

Mais 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
 

Último

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 

Último (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 

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.

Notas do Editor

  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