+ All Categories
Home > Software > JavaScript Presentation

JavaScript Presentation

Date post: 12-Aug-2015
Category:
Upload: cristi-salcescu
View: 43 times
Download: 0 times
Share this document with a friend
61
JavaScript Presentation base on JavaScript: The Good Parts by Douglas Crockford V1.0
Transcript
Page 1: JavaScript Presentation

JavaScript Presentation

base on JavaScript: The Good Parts by Douglas

CrockfordV1.0

Page 2: JavaScript Presentation

Language

• is one of the world's most popular programming languages.

• is a scripting language for Web browsers• is a dynamic computer programming language

.[5] • is a prototype-based scripting language• has first-class functions

Page 3: JavaScript Presentation

Types• A variable can hold one of two types of values: primitive values and reference values.• Primitive values are data that are stored on the stack. All primitives are immutable.• Reference values are objects that are stored in the heap.• Reference value stored in the variable is a pointer to a location in memory where the object is

stored.

• Primitive– Number– Boolean– String– undefined– null

• Reference– Array– Object– Function– Date– RegExp

Page 4: JavaScript Presentation

Numbers

• All numbers in JavaScript are 64-bit floating point numbers.

• “double”• The NaN property represents "Not-a-Number"

value. This property indicates that a value is not a legal number.

Page 5: JavaScript Presentation

Floating Point

• Binary floating-point numbers are inept at handling decimal fractions, so 0.1 + 0.2 is not equal to 0.3. This is the most frequently reported bug in JavaScript

• Fortunately, integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.

• For example : – Convert by multiplying them by 10 – Make the add– The sum can be divided by 10 to convert back

– Multiply : 0.1*10 + 0.2*10 = 1+2 = 3– Convert back : 3/10 = 0.3

Page 6: JavaScript Presentation

Number methods

• toExponential• toFixed• toLocaleString• toPrecision• toString• valueOf

Page 7: JavaScript Presentation

String

• a JavaScript string stores a series of characters like “my text".

• a string can be any text inside double or single quotes• There is no “char” type• Convert a number to a string :

– 1.toString()– “” + 1;

• Convert a string to a number– parseInt(“1”)– Number(“1”)

Page 8: JavaScript Presentation

+Operator

• The + operator can add or concatenate. Which one it does depends on the types of the parameters. If either operand is a string, it produces the other operand converted to a string. If both operands are numbers, it produces the sum. Otherwise, it converts both operands to strings and concatenates them.

Page 9: JavaScript Presentation

String methods• charAt• charCodeAt• compareLocale• concat• indexOf• lastIndexOf• localeCompare• match• replace• search• slice• split• substring• toLocaleLowerCase• toLocaleUpperCase• toLowerCase• toString• toUpperCase• trim• valueOf

Page 10: JavaScript Presentation

Boolean

• true• false

Page 11: JavaScript Presentation

Falsy values : false

• false• null• undefined• "" (empty string)• 0• NaN• All other values (including all objects) are truthy.Ex : "0" "false"

Page 12: JavaScript Presentation

==• '' == '0' // false• 0 == '' // true• 0 == '0' // true• false == 'false' // false• false == '0' // true• false == undefined // false• false == null // false• null == undefined // true• ' \t\r\n ' == 0 // true

• All of the comparisons just shown produce false with the === operator.

Page 13: JavaScript Presentation

Array

• Array inherits from Object.• indexes are converted to strings and usedas names for retrieving values.• an array literal uses []

• var arr = new Array(1,2,3)• var arr = [1,2,3]

Page 14: JavaScript Presentation

Array Methods• concat• every• filter• forEach• indexOf• join• lastIndexOf• map• pop• push• reduce• reduceRight• reverse• shift• slice• some• splice• toLocaleString• toString• unshift

Page 15: JavaScript Presentation

undefined

• The default value for variables andparameters.• The value of missing members in objects.

Page 16: JavaScript Presentation

null

• used where an object can be expected but no object is present

Page 17: JavaScript Presentation

Objects

• An object is a dynamic collection of properties.

• Every property has a key string that is unique within that object.

Page 18: JavaScript Presentation

Object literals

• var emptyObject = {};• var person = {

firstName : “Mihai”,lastName: “Popescu”

};

Page 19: JavaScript Presentation

Get, set, and delete

• get– object.name– object[expression]

• set– object.name = value;– object[expression] = value;

• delete– delete object.name– delete object[expression]

Page 20: JavaScript Presentation

Reflection

• The “for in” statement can loop over all of the property names in an object.

var name;for (propertyKey in person) {if (typeof person[propertyKey ] !== 'function') {

document.writeln(propertyKey + ': ' + person[propertyKey ]);

}}

Page 21: JavaScript Presentation

Functions

• Functions are the fundamental modular unit of JavaScript. They are used for code reuse, information hiding, and composition. Functions are used to specify the behavior of objects.

• Functions in JavaScript are objects. Objects are collections of name/value pairs having a hidden link to a prototype object

• Objects produced from object literals are linked to Object.prototype. Function objects are linked to Function.prototype (which is itself linked to Object.prototype).

Page 22: JavaScript Presentation

Functions

• May be passed as an argument to a function• May be returned from a function• May assigned to a variable• May be stored in an object or array• Function objects inherit from

Function.prototype.

Page 23: JavaScript Presentation

var statement

• Declares and initializes variables within afunction.• Types are not specified.• A variable declared anywhere within afunction is visible everywhere within thefunction.

Page 24: JavaScript Presentation

Functions

• Function statementfunction add(a, b) {

return a + b;};

• Function expressionvar add = function (a, b) {

return a + b;};

Page 25: JavaScript Presentation

Hoisting • Hoisting is JavaScript's default behavior of moving declarations to

the top.

function mymethod() { for (var i = 0; i < 10; i++) { var myvar = 5; } alert(myvar); // Will alert 5} mymethod();

Page 26: JavaScript Presentation

Hoisting• The above code is functionally equivalent

function mymethod() { var myvar = undefined; for (var i = 0; i < 10; i++) { myvar = 5; } alert(myvar); // Will alert 5} mymethod();

Page 27: JavaScript Presentation

Block scope vs function scope

function scopeTest() { for (var i = 0; i <= 5; i++) {

var inFor = i; } alert(inFor); // what happens here? alert(i); // what happens here?

} // call the function defined above scopeTest( );

Page 28: JavaScript Presentation

Return statement

• return expression;or• return;

• all functions return• If there is no expression, then the returnvalue is undefined.Except for constructors, whose default return value is this.

Page 29: JavaScript Presentation

Two pseudo parameters

• arguments• this

Page 30: JavaScript Presentation

arguments

• When a function is invoked, in addition to itsparameters, it also gets a special parametercalled arguments.• It contains all of the arguments from the

invocation.• It is an array-like object.• arguments.length is the number of arguments

passed.

Page 31: JavaScript Presentation

Example

• function sum() {var i, n = arguments.length, total = 0;for (i = 0; i < n; i += 1) {

total += arguments[i];}

return total;}var ten = sum(1, 2, 3, 4);

Page 32: JavaScript Presentation

this

• The this parameter contains a referenceto the object of invocation.

Page 33: JavaScript Presentation

Invocation

• The ( ) suffix operator surrounding zeroor more comma separated arguments.• The arguments will be bound to parameters.• If a function is called with too many arguments,

the extra arguments are ignored.• If a function is called with too few arguments,

the missing values will be undefined.• There is no implicit type checking on the

arguments.

Page 34: JavaScript Presentation

Pass by value

• JavaScript is always pass by value, never pass by reference.

• There is no "pass by reference" for any variable in JavaScript (no, not even if an object is assigned to that variable). All variables and arguments are assigned by value. If the assigned value is an object, then the value of the new variable is a reference to that object, but assigning a new value/object to the new variable will not affect the original variable.

Page 35: JavaScript Presentation

Invocation

• Ways to call a function:• Function form– functionObject(arguments)

• Method form– thisObject.methodName(arguments)– thisObject["methodName"](arguments)

• Constructor form– new FunctionObject(arguments)

• Apply form– functionObject.apply(thisObject,[arguments])

Page 36: JavaScript Presentation

this

Page 37: JavaScript Presentation

Callbacks• For example, suppose there is a sequence that begins with a user

interaction, making a request of the server, and finally displaying the server's response. The naive way to write that would be:

response = send_request (request);display(response);

• A better approach is to make an asynchronous request, providing a callback function that will be invoked when the server's response is received. An asynchronous function returns immediately, so the client isn't blocked:

send_request(request, function (response) {display(response);

});

Page 38: JavaScript Presentation

Closure

• The context of an inner function includes the scope of the outer function.

• An inner function enjoys that context evenafter the parent functions have returned.• Function scope works like block scope.

Page 39: JavaScript Presentation

Global

var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];

var digit_name = function (n) {return names[n];

};alert(digit_name(3)); // 'three'

Page 40: JavaScript Presentation

Slow

var digit_name = function (n) {var names = ['zero', 'one', 'two', 'three', 'four',

'five', 'six', 'seven', 'eight', 'nine'];return names[n];

};alert(digit_name(3)); // 'three'

Page 41: JavaScript Presentation

Closure

var digit_name = (function () {var names = ['zero', 'one', 'two', 'three', 'four',

'five', 'six', 'seven', 'eight', 'nine'];return function (n) {

return names[n];};}());alert(digit_name(3)); // 'three'

Page 42: JavaScript Presentation

Don’t make functions in a loop

for (var i...) { div_id= divs[i].id; divs[i].onclick= function () {

alert(div_id); };

}

Page 43: JavaScript Presentation

Don’t make functions in a loop

var i; function make_handler(div_id) {

return function () { alert(div_id);

}} for (i...) {

div_id= divs[i].id; divs[i].onclick= make_handler(div_id);

}

Page 44: JavaScript Presentation

Module

-Revealing Module Pattern

var module = (function() { var private = function() { // ... }; var public = function() { // ... };

return { public: public }; })(); typeof module.public; // "function" typeof module.private; // "undefined"

Page 45: JavaScript Presentation

Module

(function () { // ... all vars and functions are in this scope only // still maintains access to all globals

}());

- self-executing anonymous function- immediately-invoked function expression (or

IIFE, pronounced "iffy")

Page 46: JavaScript Presentation

Namespace• The Idea behind creating a namespace in JavaScript is simple: one global

object is created and all variables, methods and functions become properties of that object. Use of namespaces also minimizes the possibility of name conflicts in an application.

• An object is a Namespace:

• Let's create a global object called MYAPP// global namespace var MYAPP = MYAPP || {};

• We can also create sub namespace:// sub namespace MYAPP.event = {};

Page 47: JavaScript Presentation

Namespace

• Below is code syntax for creating namespace and adding variable, function and method:

• // Object together with the method declarations MYAPP.event = {

addListener: function(el, type, fn) { // code stuff }, removeListener: function(el, type, fn) { // code stuff }, getEvent: function(e) { // code stuff } // Can add another method and properties

}

Page 48: JavaScript Presentation

Function as a class : The Constructor

function Person() { alert('Person instantiated'); } var person1 = new Person(); var person2 = new Person();

Page 49: JavaScript Presentation

The Public Propertyfunction Person(firstName) {

this.firstName = firstName; alert('Person instantiated');

}

var person1 = new Person('Alice'); var person2 = new Person('Bob');

// Show the firstName properties of the objects alert('person1 is ' + person1.firstName); // alerts "person1 is Alice" alert('person2 is ' + person2.firstName); // alerts "person2 is Bob"

Page 50: JavaScript Presentation

The Methods

function Person(firstName) { this.firstName = firstName;

} Person.prototype.sayHello = function() { alert("Hello, I'm " + this.firstName); };

var person1 = new Person("Alice"); var person2 = new Person("Bob");

// call the Person sayHello method. person1.sayHello(); // alerts "Hello, I'm Alice" person2.sayHello(); // alerts "Hello, I'm Bob"

Page 51: JavaScript Presentation

Functional Inheritancefunction Person(firstName) {

this.firstName = firstName; } Person.prototype.walk = function(){ alert("I am walking!"); }; Person.prototype.sayHello = function(){ alert("Hello, I'm " + this.firstName); };

function Student(firstName, subject) { Person.call(this, firstName); this.subject = subject;

}; Student.Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; Student.prototype.sayHello = function(){ alert("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + "."); }; Student.prototype.sayGoodBye = function(){ alert("Goodbye!"); };

var student1 = new Student("Janet", "Applied Physics"); student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." student1.walk(); // "I am walking!" student1.sayGoodBye(); // "Goodbye!" alert(student1 instanceof Person); // true alert(student1 instanceof Student); // true

Page 52: JavaScript Presentation

Object : this vs thatfunction Person(){ this.fname = ""; this.lname = ""; function getName(){ return this.fname + " " + this.lname; } this.getDescription = function(){ return "Person : " + getName(); }}

var p = new Person();p.fname = "Cristi";p.lname = "S";alert(p.getDescription());

Page 53: JavaScript Presentation

Object : this vs thatfunction Person(){ var that = this; this.fname = ""; this.lname = ""; function getName(){ return that.fname + " " + that.lname; } this.getDescription = function(){ return "Person : " + getName(); }}

var p = new Person();p.fname = "Cristi";p.lname = "S";alert(p.getDescription());

Page 54: JavaScript Presentation

typeof

• The typeof prefix operator returns a string identifying the type of a value.

Page 55: JavaScript Presentation

typeof

Page 56: JavaScript Presentation

typeof

Page 57: JavaScript Presentation

Global variables

• JavaScript makes it easy to define global variables that can hold all of the data of your application

var MYAPP = {};• If you forget to use var in function you

accidentally create a global variable.function test(){ x = 3.14;}test();alert(x);

Page 58: JavaScript Presentation

Strict Mode• "use strict";• Declared at the beginning of a JavaScript file, it has global scope• Declared inside a function, it has local scope (only the code inside the

function is in strict mode).• you cannot, for example, use undeclared variables.• the this value was the global object. In strict mode, it is now

undefined.

function testStrict(){ "use strict"; x = 3.14; // This causes an error. }x = 3.14; // This does not cause an error.

Page 59: JavaScript Presentation

Semicolon Insertionreturn{

status: true};• This appears to return an object containing a status member.

Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:

return {status: true

};

Page 60: JavaScript Presentation

Exception• JavaScript provides an exception handling mechanism.

function try_it ( ) {try {

add("seven");} catch (e) {document.writeln(e.name + ': ' + e.message);}

}tryIt( );

• If an exception is thrown within a try block, control will go to its catch clause.• A try statement has a single catch block that will catch all exceptions. If your handling

depends on the type of the exception, then the exception handler will have to inspect the name to determine the type of the exception.


Recommended