Java script Techniques Part I

Post on 18-Jul-2015

238 views 0 download

Transcript of Java script Techniques Part I

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 declaredfunction 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 SettersECMAScript 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.