Date post: | 12-Aug-2015 |
Category: |
Software |
Upload: | cristi-salcescu |
View: | 43 times |
Download: | 0 times |
JavaScript Presentation
base on JavaScript: The Good Parts by Douglas
CrockfordV1.0
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
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
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.
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
Number methods
• toExponential• toFixed• toLocaleString• toPrecision• toString• valueOf
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”)
+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.
String methods• charAt• charCodeAt• compareLocale• concat• indexOf• lastIndexOf• localeCompare• match• replace• search• slice• split• substring• toLocaleLowerCase• toLocaleUpperCase• toLowerCase• toString• toUpperCase• trim• valueOf
Boolean
• true• false
Falsy values : false
• false• null• undefined• "" (empty string)• 0• NaN• All other values (including all objects) are truthy.Ex : "0" "false"
==• '' == '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.
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]
Array Methods• concat• every• filter• forEach• indexOf• join• lastIndexOf• map• pop• push• reduce• reduceRight• reverse• shift• slice• some• splice• toLocaleString• toString• unshift
undefined
• The default value for variables andparameters.• The value of missing members in objects.
null
• used where an object can be expected but no object is present
Objects
• An object is a dynamic collection of properties.
• Every property has a key string that is unique within that object.
Object literals
• var emptyObject = {};• var person = {
firstName : “Mihai”,lastName: “Popescu”
};
Get, set, and delete
• get– object.name– object[expression]
• set– object.name = value;– object[expression] = value;
• delete– delete object.name– delete object[expression]
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 ]);
}}
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).
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.
var statement
• Declares and initializes variables within afunction.• Types are not specified.• A variable declared anywhere within afunction is visible everywhere within thefunction.
Functions
• Function statementfunction add(a, b) {
return a + b;};
• Function expressionvar add = function (a, b) {
return a + b;};
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();
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();
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( );
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.
Two pseudo parameters
• arguments• this
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.
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);
this
• The this parameter contains a referenceto the object of invocation.
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.
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.
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])
this
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);
});
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.
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'
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'
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'
Don’t make functions in a loop
for (var i...) { div_id= divs[i].id; divs[i].onclick= function () {
alert(div_id); };
}
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);
}
Module
-Revealing Module Pattern
var module = (function() { var private = function() { // ... }; var public = function() { // ... };
return { public: public }; })(); typeof module.public; // "function" typeof module.private; // "undefined"
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")
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 = {};
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
}
Function as a class : The Constructor
function Person() { alert('Person instantiated'); } var person1 = new Person(); var person2 = new Person();
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"
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"
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
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());
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());
typeof
• The typeof prefix operator returns a string identifying the type of a value.
typeof
typeof
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);
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.
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
};
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.
Bibliography
• JavaScript: The Good Parts by Douglas Crockford
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript