coffee script
DESCRIPTION
Fast introduction to Coffee Script, a valid alternative to Java Script.TRANSCRIPT
JavaScript “bien hecho”Yeray Darias
CoffeeScript
Antes de CoffeeScript fue JavaScript
Un poco de historia reciente
Finales del año 1994 ...
En el año 1995 ...
Brendan Eich idea y programa
10 DíasMocha en apenas
Mocha
LiveScript
JavaScript
Allá por el año 1997 ...
A principios del 2000 ...
JavaScript tenía algunos amigos pero no era muy popular
En la actualidad ...
JavaScript está en todas partes
Javascript
¿Qué demonios es CoffeeScript?
Pongamonos en situación
Es una idea que tuvo
“CoffeeScript it’s just JavaScript”
CoffeeScript esun lenguaje de programación
que “genera”
JavaScript
JavaScript WTFs
Douglas CrockfordJavaScript
The good parts
Global variables
CoffeeScript solved!
var message = “hola”;!!function saluda() {! return message;!}
var message = “adios”;!!function despidete() {! return message;!}
Global variables
Si ambos ficheros están “cargados”, ¿Cuál es la salida esperada en cada
función?
Global variables
CoffeeScript no crea variables globales de forma implícita
(function() {! var message, saluda;!! message = "hola";!! saluda = function() {! return message;! };!}).call(this);
message = "hola"!!saluda = () -> ! message
Scopes
Scopes
Todas las variables en una función se declaran al principio
(function() {! var message, saluda;!! message = "hola";!! saluda = function() {! return message;! };!}).call(this);
message = "hola"!!saluda = () -> ! message
Semicolons
CoffeeScript solved!
Semicolons
CoffeeScript autocompleta los ;
(function() {! var message, saluda;!! message = "hola";!! saluda = function() {! return message;! };!}).call(this);
message = "hola"!!saluda = () -> ! message
Reserved words
CoffeeScript solved!
Reserved words
CoffeeScript escapa las palabras reservadas automáticamente
var myObject;!!myObject = {! "case": 'keyword',! tutu: 'allowed name'!};
myObject = ! case: 'keyword'! tutu: 'allowed name'
typeof
Equality comparisons
CoffeeScript solved!
Equality comparisons
CoffeeScript siempre usa los operadores como ===, !==, ...
var testFunction;!!testFunction = function(input) {! if (input === 'string') {! 'string';!! }! if (input === 9) {! return 'number nine';! }!};
testFunction = (input) -> ! if (input == 'string')! 'string'! if (input == 9)! 'number nine'
eval()
continue
switch fall through
CoffeeScript solved!
switch fall throughBond = (input) -> ! switch input! when 'Sean Connery', 'Daniel Craig'! 'Fucking crack'! when 'Roger Moore'! 'A bit boring'
var Bond;!!Bond = function(input) {! switch (input) {! case 'Sean Connery':! case 'Daniel Craig':! return 'Fucking crack';! case 'Roger Moore':! return 'A bit boring';! }!};!
Todas las opciones acaban con un return
Global variablesScopesSemicolonsReserved wordstypeofEquality comparisoneval()continueSwitch fall through
CoffeeScript “fabrica”
bloques JavaScript
Control de flujomood = greatlyImproved if singing!!if happy and knowsIt! clapsHands()!else! showIt()!!date = if friday then sue else jill!!isToday = yes unless yesterday or tomorrow!!// -----------------------------------------------------!!cholesterol = 127!!healthy = 200 > cholesterol > 60!
Chained comparisons
Everything a expression
Control de flujo
Bond = (input) -> ! switch input! when 'Sean Connery', 'Daniel Craig'! 'Fucking crack'! when 'Roger Moore'! 'A bit boring'! else! 'No comments'
Bucles# Health conscious meal.!foods = ['broccoli', 'spinach', 'chocolate']!eat food for food in foods when food isnt 'chocolate'!!countdown = (num for num in [10..1])!!# Econ 101!if this.studyingEconomics! buy() while supply > demand! sell() until supply > demand!!while age < 18! canNotSmoke()! canNotDrink()
Funcionessquare = (x) -> x * x!cube = (x) -> square(x) * x!!fill = (container, liquid = "coffee") ->! "Filling the #{container} with #{liquid}..."!!// --------------------------------------------------!!awardMedals = (first, second, others...) ->! gold = first! silver = second! rest = others!!!
Splats
String interpolation
Operators & aliasesCoffeeScript JavaScript
is ===isnt !==not !and &&or ||
true, yes, on truefalse, no, off false
@, this thisof inin no JS equivalent
‘The’ operator
? es el operador existencial en
CoffeeScript
Clasesclass Animal! constructor: (@name) ->!! move: (meters) ->! alert @name + " moved #{meters}m."!!class Snake extends Animal! move: ->! alert "Slithering..."! super 5!!class Horse extends Animal! move: ->! alert "Galloping..."! super 45
Clases!!sam = new Snake "Sammy the Python"!tom = new Horse "Tommy the Palomino"!!sam.move()!tom.move()!
Function bindingAccount = (customer, cart) ->! @customer = customer! @cart = cart!! $('.shopping_cart').bind 'click', (event) =>! @customer.purchase @cart!!var Account;!!Account = function(customer, cart) {! var _this = this;! this.customer = customer;! this.cart = cart;! return $('.shopping_cart').bind('click', function(event) {! return _this.customer.purchase(_this.cart);! });!};!
Ahora toca programar