mejorando.la: curso profesional de frontend, dominando javascript
DESCRIPTION
JavaScript las partes feas y geniales, y patronesTRANSCRIPT
Dominando JavaScript
por David Avellaneda @davsket
@davsket?
acerca de mi
• Ingeniero de Sistemas…
• Cofundador de monoku y monomi.co
• Co-organizador de BogotáJS
• Co-organizador de JSConf.co
Agenda
Agenda
• JavaScript: Las partes buenas
• JavaScript Orientado a Objetos (OO)
• Closures, Mixins, Objetos, Prototipos
• Patrones de Diseño y MV*
• APIs Rest, AJAX y Sockets (*)
JavaScript: Las Partes Buenas
Recomendación: Compren el Libro
Las Partes Buenas?
JavaScript: The Good Parts 80% Intro a JS
2% Hermosas características 10% Feas características
10% Malas partes
Las Partes Feas
Scope
var a = 5, b = 10 !function noGlobal( a ){ var b = 3 a = a*2 return a * b } !noGlobal( 1 ) // 6 a // 5 b // 3
typeof
typeof new Number(8) == "object" typeof 8 == "number"
parseInt
parseInt ¡cuidado con los legacy browsers!
parseInt( "08" ) // 0 parseInt( "08", 10 ) // 8
!Chrome ya no...
Números Flotantes
Gracias a "Binary Floating-Point Arithmetic (IEEE 754)"
!0.1 + 0.2 != 0.3
Valores Falsos (abstract equality comparison)
'' == '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
'' === '0' // false 0 === '' // false 0 === '0' // false !false === 'false' // false false === '0' // false !false === undefined // false false === null // false null === undefined // false !' \t\r\n ' === 0 // false
hasOwnProperty
Cualquiera puede modificar el prototipo y generarte problemas!
with
var a = { p: 0 }, c !with( a ){ p = 3 c = 5 } !a.p // 3 a.c // undefined c // 5
eval
No es tan maaaalo como lo pintan!
eval("myValue = myObject." + myKey + ";");
en vez de:
myvalue = myObject[myKey]
No usen eval para ejecutar código desde el servidor u otro servicio AJAX
switch
... fall through .. !
va de case en case naturalmente (requiere usar break)
valida con equivalencia simple
var blah = 0; switch (blah) { case -1: alert('negative 1'); case 0: alert(0) case 1: alert(1); break; case 2: alert(2); break; default: alert('default'); }
Doble Filo!!
Punto y Coma Opcional (optional semicolon)
!- Código más limpio -
Declaraciones Sin Corchetes (block-less statements)
if( a ){ a.b = 3 }
if( a ) a.b = 3
if( a ){ a.b = 3 a.c = 4 }
if( a ) a.b = 3 a.c = 4
if( a ){ a.b = 3 } a.c = 4
++ --
var a = [1,2,3,4], i = 0 a[i++] // 1 a[++i] // 3
new
"this"
métodos vs funciones
hoisting
el orden de definición de variables y funciones afecta el resultado
function f(){ alert( a ) a = 5 } f()
function f(){ alert( a ) a = 5 } f() // ReferenceError a is not defined
function f(){ alert( a ) var a = 5 } f()
function f(){ alert( a ) var a = 5 } f() // undefined
function f(){ var a alert( a ) a = 5 } f() // undefined
var a = 10 !function f(){ alert( a ) var a = 5 } !f()
var a = 10 !function f(){ alert( a ) var a = 5 } !f() // undefined
var a = 10 !function f(){ var a alert( a ) a = 5 } !f() // undefined
var a = 10 !function f(){ a = 5 alert( a ) function a(){} } !f() // ? a // ?
var a = 10 function f(){ a = 5 alert( a ) function a(){} } f() // 5 a // ?
var a = 10 function f(){ a = 5 alert( a ) function a(){} } f() // 5 a // 5 ? no... 10!!
The Cool Parts + Patterns
Prototype
JavaScript es Orientado a Objetos (OO) pero no tiene
Clases !
JavaScript es basado en Prototipos
functions con prototype
function Persona( name ){ this.name = name } Persona.prototype.alertName = function(){ alert( this.name ) } Persona.prototype.setAge = function( age ){ this.age = age } var juan = new Persona( 'juan' )
juan.alertName() // juan juan.setAge( 25 ) !Persona.prototype.sayYolo = function(){ alert(this.name + ': YOLO!') } !juan.sayYolo() // juan: YOLO!
Object.create( proto, properties )
constructor
juan.constructor // function Persona( ...
juan.__proto__
Function are first-class objects
¿first-class objects?
• se pueden asignar a variables
• se puede recibir/pasar como argumentos
• se pueden retornar en una función
• son objetos y por lo tanto tienen propiedades
Function are first-class objects
=> Chain
Callback Observable Delegation
Closure MVC
MVVM MV*
Chain
var o = { i: 0, f: function(){ ++ this.i return this } } o.f().f().f() o.i // 3
$('#myelem') .hide() .css({..}) .data(..) .fadeIn(..)
Callback ( Async ) "las funciones pueden ser pasadas
como argumentos"
Es como una sala de espera en la que dependiendo del turno tu puedes ser llamado
function caller( cb ){ setTimeout(function(){ cb( new Date() ) }, 1000) } caller(function( now ){ alert( now ) })
$(document).on('click', click) function click(){ alert('auch!') }
$.ajax({ url: ".", type: "get" }) .done(function(){ console.log("async!") }) console.log("sync")
Observable + "y Las funciones pueden asignarse a variables"
Este patrón permite que diferentes interesados se suscriban a un objeto escuchando eventos
Delegación
Observar cientos de elementos con cientos de
eventListeners no es recomendable
Aplica en listados
document.getElementById("parent-list") .addEventListener("click",function(e) { if(e.target && e.target.nodeName == "LI") { console.log("List item ", e.target.id.replace("post-")," was clicked!"); } });
$('#padre').on('click', '.hijo', callback)
Closures
se reduce a: invocación inmediata de
funciones
(function(){ var hidden = 8 }()) !console.log( typeof hidden ) // undefined
MVC / MVVM / MV*
Sfotipy!
Sfotipy!
• Agregar jQuery
• Crear nuestro Modelo
• Crear nuestra Vista
• Crear nuestro Controlador
• Observables!
Gracias!!