Javascript: Funciones
var x = function (a, b) {return a * b};
En JS, no hay chequeo de tipo ni de número de parámetros
Javascript: Funciones
var x = function (a, b) {return a * b};
var z = x(4);
var z = x();?
En JS, no hay chequeo de tipo ni de número de parámetros
Javascript: Funciones
var x = function (a, b) {return a * b};
var z = x(4);
var z = x();
En JS, no hay chequeo de tipo ni de número de parámetros
NaN
NaN
Javascript: Funciones
var someFunction = function() {…};someOtherFunction(someFunction);
En JS, las funciones pueden ser argumentos de otras funciones
someOtherFunction(function(){…});
Ejemplo: la función every
var ages = [32, 33, 16, 40];
function checkAdult(age) { return age >= 18;}
function myFunction() { document.getElementById("demo").innerHTML = ages.every(checkAdult);}
myFunction();
Ejemplo: la función every
var ages = [32, 33, 16, 40];
function checkAdult(age) { return age >= 18;}
function myFunction() { document.getElementById("demo").innerHTML = ages.every(checkAdult);}
myFunction();
La función every verifica que todos los elementos en un arreglo pasan una prueba que es proporcionada como parámetro
Ejemplo: la función forEach
<script>
var numbers = [4, 9, 16, 25];
function myFunction(item, index) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
Ejemplo: la función forEach
<script>
var numbers = [4, 9, 16, 25];
function myFunction(item, index) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
index[0]: 4index[1]: 9index[2]: 16index[3]: 25
Ejemplo: la función forEach
<script>
var numbers = [4, 9, 16, 25];
function myFunction(index, item) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
Ejemplo: la función forEach
<script>
var numbers = [4, 9, 16, 25];
function myFunction(index, item) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
index[4]: 0index[9]: 1index[16]: 2index[25]: 3
Ejemplo: la función forEach
<!DOCTYPE html><html><body>
<script>var numbers = [4, 9, 16, 25];
function myFunction(item) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
</body></html>
Ejemplo: la función forEach
<!DOCTYPE html><html><body>
<script>var numbers = [4, 9, 16, 25];
function myFunction(item) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
</body></html>
?
Ejemplo: la función forEach
<!DOCTYPE html><html><body>
<script>var numbers = [4, 9, 16, 25];
function myFunction(item) { console.log("index[" + index + "]: " + item); }
numbers.forEach(myFunction)</script>
</body></html>
>> Uncaught ReferenceError: index is not defined
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body><script>function testArg(){
var msg = "Hola";function innerCall(){
console.log(msg);}
innerCall();}testArg();</script>
</body></html>
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body><script>function testArg(){
var msg = "Hola";function innerCall(){
console.log(msg);}
innerCall();}testArg();</script>
</body></html>
>>Hola
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body>
<script>var chapter = {
num:7,title: "Function in object",getNum: function(){return num}
};console.log(chapter.getNum());</script>
</body></html>
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body>
<script>var chapter = {
num:7,title: "Function in object",getNum: function(){return num}
};console.log(chapter.getNum());</script>
</body></html>
>>Uncaught ReferenceError: num is not defined
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body>
<script>var chapter = {
num:7,title: "Function in object",getNum: function(){return this.num}
};console.log(chapter.getNum());</script>
</body></html>
Funciones: Invocaciones anidadas
<!DOCTYPE html><html><body>
<script>var chapter = {
num:7,title: "Function in object",getNum: function(){return this.num}
};console.log(chapter.getNum());</script>
</body></html>
>>7
Excepciones
try{ …}catch(error){…}finally{ …}
try{ …}catch(error){console.log(error.name);console.log(error.message);}
Excepciones
throw 2; >> Uncaught 2
throw "Something is wrong"; >> Uncaught Something is wrong
throw Error("This is an error"); >> Uncaught Error: This is an error
throw {name:'Error', message:'Ooops'};>> Uncaught [object Object]
Excepciones
<!DOCTYPE html><html><body>
<script>function test(){ throw 2; throw "Something is wrong"; throw Error("This is an error"); throw {name:'Error', message:'Ooops'};}
test();</script>
</body></html>
?
Prototipos
Prototipo: Plantilla de objetos definidas como una función constructora con atributos internos
function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor;}
Prototipos
Prototipo: Plantilla de objetos definidas como una función constructora con atributos internos
function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor;}
var myFather = new Person("John", "Doe", 50, "blue");var myMother = new Person("Sally", "Rally", 48, "green");
Prototipos
Se pueden agregar métodos a los prototipos en tiempo de ejecución
function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor;}
var mario = new Person('Mario', 'Linares', '??', 'hazel');
Person.prototype.name = function() {return this.firstName+" "+ this.lastName};
console.log(mario.name());
Closures
- Función con memoria y variables privadas
- Definición encadenada de funciones, en la que la segunda (anónima) tiene acceso al contexto de la primera
- Las funciones “closure” tienen acceso a tres scopes:
local, función padre, y global
- Las funciones “closure” acceden a las variables de la función padre incluso después de ejecutada
Closures
<script>
var add = function () { var counter = 0; return counter += 1;};
console.log(add());console.log(add());console.log(add());
</script>
Closures
<script>
var add = function () { var counter = 0; return counter += 1;};
console.log(add());console.log(add());console.log(add());
</script>
<script>var counter = 0;var add = function () { return counter += 1;};
console.log(add());console.log(add());console.log(add());
</script>
Closures
<script>
var add = function () { var counter = 0; return function () {return counter += 1;}};
console.log(add());console.log(add());console.log(add());
</script>
Closures
<script>
var add = function () { var counter = 0; return function () {return counter += 1;}};
console.log(add());console.log(add());console.log(add());
</script>
>> function () {return counter += 1;}>> function () {return counter += 1;}>> function () {return counter += 1;}
Closures
<script>
var add = (function () { var counter = 0; return function () {return counter += 1;}};)()
console.log(add());console.log(add());console.log(add());
</script>
Closures
<script>
var add = (function () { var counter = 0; return function () {return counter += 1;}};)()
console.log(add());console.log(add());console.log(add());
</script>
>> 1>> 2>> 3
Closures
//function declaration (statement)function bar() { return 3;}
//anonymous function expressionvar a = function() { return 3;} //named function expressionvar a = function bar() { return 3;} //immediately invoked function expression (IIFE)(function sayHello() { alert("hello!");})();
Obligatorio leer: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
Mas Javascript…
function one(){ function two() { return 2; } return two(); function two() { return 3; }}alert(one());
function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}alert(one());
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Mas Javascript…
function one(){ function two() { return 2; } return two(); function two() { return 3; }}alert(one());
function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}alert(one());
>>3
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Mas Javascript…
function one(){ function two() { return 2; } return two(); function two() { return 3; }}alert(one());
function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}alert(one());
>>3 >>2
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Mas Javascript…
alert(one());function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}
function one(){ return two(); var two = function() { return 3; }; var two = function() { return 3; };}alert(one());
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Mas Javascript…
alert(one());function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}
function one(){ return two(); var two = function() { return 3; }; var two = function() { return 3; };}alert(one());
>>2
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Mas Javascript…
alert(one());function one(){ var two = function() { return 2; }; return two(); var two = function() { return 3; };}
function one(){ return two(); var two = function() { return 3; }; var two = function() { return 3; };}alert(one());
>>2>>Uncaught TypeError: two is not a function
Obligatorio leer: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Promesas (Promises)
Declaración de ejecuciones futuras condicionales, asociadas con llamadas asíncronas o síncronas éxito/fallo:
p.then(e, f)
Promesas (Promises)
p.then(e, f)
Función a ejecutar como parte de la promesa
Declaración de ejecuciones futuras condicionales, asociadas con llamadas asíncronas o síncronas éxito/fallo:
Promesas (Promises)
p.then(e, f)
Comportamiento a ejecutar en caso de éxito
Declaración de ejecuciones futuras condicionales, asociadas con llamadas asíncronas o síncronas éxito/fallo:
Promesas (Promises)
p.then(e, f)
Comportamiento a ejecutar en caso de fallo
Declaración de ejecuciones futuras condicionales, asociadas con llamadas asíncronas o síncronas éxito/fallo:
Promesas (Promises)
var promise = new Promise(function(resolve, reject) { …..
if (success) { resolve(…); } else { reject(…); }});
Expresión usando el constructor Promise
Promesas (Promises)
var promise = new Promise(function(resolve, reject) { …..
if (success) { resolve(…); } else { reject(…); }});
Expresión usando el constructor Promise
Promesas (Promises)
Definición de los métodos a ejecutar con la promesa
promise.then(function(result) { console.log(result); // Caso de éxito}, function(err) { console.log(err); // Caso de error}
);
Ejemplo
function get(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url);
req.onload = function() { if (req.status == 200) {
resolve(req.response); } else { reject(Error(req.statusText)); } }; req.send(); });}
Tomado de https://developers.google.com/web/fundamentals/getting-started/primers/promises
Ejemplo
get('story.json').then(function(response) { console.log("Success!", response);}, function(error) { console.error("Failed!", error);});
Tomado de https://developers.google.com/web/fundamentals/getting-started/primers/promises
Encadenamiento
Tomado de https://developers.google.com/web/fundamentals/getting-started/primers/promises
p.then(e).then(e)…
var promise = new Promise(function(resolve, reject) { resolve(1);});
promise.then(function(val) { console.log(val); // 1 return val + 2;}).then(function(val) { console.log(val); // 3})