Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A linguagem JavaScript

talles
March 25, 2015

A linguagem JavaScript

talles

March 25, 2015
Tweet

More Decks by talles

Other Decks in Programming

Transcript

  1. Características & História “The idea was to make something that

    Web designers, people who may or may not have much programming training, could use to add a little bit of animation or a little bit of smarts to their Web forms and their Web pages.”
  2. Características & História “If I had done classes in JavaScript

    back in May 1995, I would have been told that it was too much like Java or that JavaScript was competing with Java … I was under marketing orders to make it look like Java but not make it too big for its britches … [it] needed to be a silly little brother language.”
  3. Características & História “When I was a young journeyman programmer,

    I would learn about every feature of the languages I was using, and I would attempt to use all of those features when I wrote. I suppose it was a way of showing off, and I suppose it worked because I was the guy you went to if you wanted to know how to use a particular feature. Eventually I figured out that some of those features were more trouble than they were worth. Some of them were poorly specified, and so were more likely to cause portability problems. Some resulted in code that was difficult to read or modify. Some induced me to write in a manner that was too tricky and error-prone. And some of those features were design errors. Sometimes language designers make mistakes.”
  4. Características & História “Most programming languages contain good parts and

    bad parts. I discovered that I could be a better programmer by using only the good parts and avoiding the bad parts. After all, how can you build something good out of bad parts?”
  5. Características & História “JavaScript’s functions are first class objects with

    (mostly) lexical scoping. JavaScript is the first lambda language to go mainstream. Deep down, JavaScript has more in common with Lisp and Scheme than with Java. It is Lisp in C’s clothing. This makes JavaScript a remarkably powerful language.”
  6. Node.js “I had several failed private projects doing the same

    on C, Lua, and Haskell. Haskell is pretty ideal but I'm not smart enough to hack the GHC. Lua is less ideal but a lovely language - I did not like that it already had a lot of libraries written with blocking code. No matter what I did, someone was going to load an existing blocking Lua library in and ruin it. C has similar problems as Lua and is not as widely accessible.”
  7. Node.js “V8 came out around the same time I was

    working on these things and I had a rather sudden epiphany that JavaScript was actually the perfect language for what I wanted: single threaded, without preconceived notions of "server-side" I/O, without existing libraries.”
  8. Node.js “We've been working with Joyent since July to try

    and move the project to a structure where the contributors and community can step in and effectively solve the problems facing Node [including the lack of active and new contributors and the lack of releases]. My guess is that Fedor was tired of waiting and set io.js up. He didn't promote it or anything, but those of us who were close enough saw it and jumped on. Then we moved all the Node core-related Node Forward work over, which has been building for some time but can't do a release due to trademark restrictions.”
  9. Variáveis var a = 'a' // a = 'a' var

    foo = 1 // a = 'a', foo = 1 foo = 'bar' // a = 'a', foo = 'bar' a = foo = '123' // a = '123', foo = '123'
  10. Ponto e vírgula é opcional a = b + c

    (d + e) // c is not a function
  11. Operadores • Aritméticos: +, -, *, /, %, ++, --;

    • Atribuição: =, +=, -=, *=, /=, %=; • Comparação: =, !=, >, >=, <, <=, ===, !==; • Lógicos: !, ||, &&, ? :; • Bitwise: &, |, ^, <<, >>, >>>, ~; • String: =, +, +=.
  12. Condições & Loops if (expressão) { // instrução } else

    if (expressão) { // instrução } else { // instrução }
  13. Condições & Loops switch (expressao) { case algum valor: //

    instrução break case outro valor: // instrução break default: // instrução break }
  14. Condições & Loops while (condicao) { // instrução } do

    { // instrução } while (condição)
  15. Palavras reservadas break, case, catch, class*, const*, continue, debugger, default,

    delete, do, else, enum*, export*, extends*, finally, for, function, if, implements*, import*, in, instanceof, interface*, let*, new, package*, private*, protected*, public*, return, static*, super*, switch, this, throw, try, typeof, var, void, while, with, yield*. * Reservadas para uso futuro.
  16. Boolean Qualquer tipo pode ser utilizado em uma expressão booleana,

    eles são automaticamente convertidos para Boolean. 0, -0, null, NaN, undefined, '' são considerados false. Strings não vazias (como '0' ou 'false') são sempre consideradas true. Tais conversões não funcionam quando comparado com === ou !==.
  17. Objetos podem ser aninhados var compra = { item: 'churros',

    quantidade: 1, cliente: { nome: 'fulano', idade: 30 } }
  18. Propriedades podem conter espaços var fulano = { nome: 'fulano',

    idade: 30, 'data de nascimento': new Date(1985, 0, 1) }
  19. Propriedades fulano.nome // acessando fulano['nome'] // acessando de outra maneira

    fulano.altura = 175 // criando uma nova propriedade delete fulano.idade // removendo uma propriedade
  20. Iterando sobre propriedades for (var prop in fulano) { //

    prop é a chave // fulano[prop] é o valor }
  21. Objetos são passados por referência function bloquear (o) { o.bloqueado

    = true } // após a chamada abaixo, obj passará a ter a propriedade bloqueado bloquear(obj)
  22. JSON é mais restritivo • Não existe undefined; • Nome

    das propriedades devem ser sempre strings; • String com ' (aspas simples) são inválidas; • Não aceita funções; • Não aceita Date; • Não aceita Regex.
  23. Funções // sempre retornam algum valor // undefined no exemplo

    abaixo function hello () { console.log('Hello world!') }
  24. Cidadãs de primeira classe Pode-se: • Armazenar uma função em

    uma variável; • Passar funções como parâmetro; • Criar funções anônimas; • Aninhar funções; • Enclausurar variáveis.
  25. Closure function lembrar (mensagem) { var lembrete = 'Lembrete: '

    + mensagem setInterval(function () { console.log(lembrete) }, 5000) } lembrar('o JavaScript "guardou" a variável local!')
  26. arguments function ImprimoQualquerCoisa () { for (var i = 0;

    i < arguments.length; ++i) { console.log(arguments[i]) } } ImprimoQualquerCoisa() ImprimoQualquerCoisa(1, 2, 3) ImprimoQualquerCoisa(undefined)
  27. Manipulando seus elementos var array = [ 'zero', 'um', 'dois'

    ] array.push('três') console.log(array[3]) // três array.pop() console.log(array[3]) // undefined
  28. for for (var i = 0; i < nomes.length; ++i)

    { console.log(nomes[i]) }
  29. every function nomePreenchido (nome) { return !!nome } // true

    se todos nomes nomes.every(nomePreenchido) // estiverem preenchidos
  30. reduce function soma (a, b) { return a + b

    } precos.reduce(soma) // total dos preços
  31. Extras Alguns temas que não estavam na apresentação. • Orientação

    a Objetos (construtores, membros privados, herança…) • Date; • Regex; • eval; • use strict; • with; • Hoisting; • Currying; • ES6.