Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
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 in...
© 2014 Citrix. Confidential.3
JavaScript today
• Language of the Year 2014!
• Frameworks
• Backbone.js
• JavaScriptMVC
• *...
© 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 = l...
© 2014 Citrix. Confidential.8
Prototype
• A prototype is an object from which other objects inherit properties
• Prototype...
© 2014 Citrix. Confidential.9
Dissecting an Object
person Object
person
[[Prototype]]
Object
constructor
hasOwnProperty
is...
© 2014 Citrix. Confidential.10
Constructors
Content borrowed from Bala’s presentation
When a function is called with the n...
© 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 ob...
© 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 o...
© 2014 Citrix. Confidential.16
Coercion
var Twelve = new Number(12);
var fifteen = Twelve + 3;
fifteen; //15
typeof fiftee...
© 2014 Citrix. Confidential.17
Keep in mind…
• Do not try to extend native objects: Number, Array, etc
• Affects Globally
...
Functions
© 2014 Citrix. Confidential.19
Parameter Passing
• Objects pass by reference
• Arrays
• Objects
• null
• Primitives pass b...
© 2014 Citrix. Confidential.20
JavaScript Functions
• JS unit of abstraction and behavior
• First-class objects ≈ a value ...
© 2014 Citrix. Confidential.21
JavaScript Functions as First-Class Objects
var someFunc = function () { return ”ABC"}; // ...
© 2014 Citrix. Confidential.22
JavaScript Functions as First Class objects2
function someFunc(otherFunc) { // as argument ...
Closures
© 2014 Citrix. Confidential.24
Function’s Closure
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5...
© 2014 Citrix. Confidential.25
Emulating Private Methods
var counter = (function() {
var privateCounter = 0;
function chan...
© 2014 Citrix. Confidential.26
Duck Typing
function myArray() { }
MyArray.prototype.length = 0;
(function() {
var methods ...
Scope
© 2014 Citrix. Confidential.28
Function Level Scope
• Scope changes inside functions
• This is JavaScript’s main scoping r...
© 2014 Citrix. Confidential.29
Global Scope
• Declared outside the context of a
function
• All functions and modules have ...
© 2014 Citrix. Confidential.30
Block Scope
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
...
© 2014 Citrix. Confidential.31
Block Scope2
- More Hoisting
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b(...
© 2014 Citrix. Confidential.32
Block Scope3
- Let
if (x > y) {
let gamma = 12.7 + y;
i = gamma * x;
}
gamma only exists in...
© 2014 Citrix. Confidential.33
Remember with?
© 2014 Citrix. Confidential.34
BAD
PRACTICE
var someFunc = function () { return "ABC"};
var myObj = {
someProp = 4,
someFu...
Enterprise-class JavaScript Applications
© 2014 Citrix. Confidential.36
AngularJS
• Open Source web application framework maintained
by Google
• Client side MVC
• ...
© 2014 Citrix. Confidential.37
Great JS Libraries
• Writing Object Oriented JS
• Prototype.js
• Backbone.js
• Ember.js
• W...
New Language Features
© 2014 Citrix. Confidential.39
Strict Mode
• Opt in to a restricted variant of JavaScript
• Eliminate silent errors by cha...
© 2014 Citrix. Confidential.40
Getters and Setters
ECMAScript 5
var obj = {
get foo() {
return 'getter';
},
set foo(value)...
© 2014 Citrix. Confidential.41
Arrow Functions (lambdas)
Implement the … operator.
Syntax:
() => { };
Java 8 recently intr...
© 2014 Citrix. Confidential.42
Variadic Functions
Implement the … operator.
Syntax:
function* name(
[param[, param[, ... p...
© 2014 Citrix. Confidential.43
Array Comprehension
Very popular in Python and
Perl
Shorten operations on multiple
items
Fo...
next.call(this,
‘Advanced JavaScript Techniques’);
part = ‘II’;
© 2014 Citrix. Confidential.45
Covers
•Functions Invocation
•Dynamic Scoping
•Functional Programming
• Why?
• Benefits
• T...
Resources
© 2014 Citrix. Confidential.47
Great Resources
• http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/...
© 2014 Citrix. Confidential.48
WORK BETTER. LIVE BETTER.
Prochain SlideShare
Chargement dans…5
×

Java script Techniques Part I

673 vues

Publié le

Part I of a presentation on Advanced Concepts in JavaScript. Cover topics like: objects, functions, closures, inheritance, new platform features, and much more.

Read more: http://luisatencio.net

Publié dans : Logiciels
  • Soyez le premier à commenter

Java script Techniques Part I

  1. 1. presentation.call(this, ‘Advanced JavaScript Techniques’); part = ‘I’; Luis Atencio Technical Readiness and Enablement
  2. 2. © 2014 Citrix. Confidential.2 General Purpose Programming Language Interpreted Single Threaded Functional Non-classical inheritance Web Maintained by ECMA Group JavaScript is…
  3. 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. 4. © 2014 Citrix. Confidential.4 “” “JavaScript is a misunderstood language” Douglas Crockford PayPal
  5. 5. © 2014 Citrix. Confidential.5 OBJECTS CLOSURES FUNCTIONS To become a JavaScript expert you need to understand
  6. 6. “Everything is an Object” Objects and Inheritance
  7. 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. 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. 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. 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. 11. © 2014 Citrix. Confidential.11 Prototype vs __proto__
  12. 12. © 2014 Citrix. Confidential.12 var bob = Person('Bob'); bob instanceof Person //false FORGETTING TO CALL new
  13. 13. © 2014 Citrix. Confidential.13 instance prototype constructor.prototype Superclass… Undefined constructor.prototype var obj = new Object(); alert (obj.toString()); Object
  14. 14. © 2014 Citrix. Confidential.14 Subclass.prototype = new SuperClass();
  15. 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. 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. 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
  18. 18. Functions
  19. 19. © 2014 Citrix. Confidential.19 Parameter Passing • Objects pass by reference • Arrays • Objects • null • Primitives pass by value • Strings • Numbers
  20. 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. 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. 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”; } };
  23. 23. Closures
  24. 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. 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. 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. 27. Scope
  28. 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. 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. 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. 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. 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. 33. © 2014 Citrix. Confidential.33 Remember with?
  34. 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 }
  35. 35. Enterprise-class JavaScript Applications
  36. 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. 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
  38. 38. New Language Features
  39. 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. 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. 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. 42. © 2014 Citrix. Confidential.42 Variadic Functions Implement the … operator. Syntax: function* name( [param[, param[, ... param]]]) { statements } ECMAScript 6
  43. 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
  44. 44. next.call(this, ‘Advanced JavaScript Techniques’); part = ‘II’;
  45. 45. © 2014 Citrix. Confidential.45 Covers •Functions Invocation •Dynamic Scoping •Functional Programming • Why? • Benefits • Techniques
  46. 46. Resources
  47. 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. 48. © 2014 Citrix. Confidential.48 WORK BETTER. LIVE BETTER.

×