Share
Embed
A linguagem JavaScript
talles
March 25, 2015
Transcript
60 slides
-
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.” -
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.” -
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.” -
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?” -
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.” -
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.” -
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.” -
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.” -
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' -
Ponto e vírgula é opcional function add (a, b) {
return a + b } -
Ponto e vírgula é opcional a = b + c
(d + e) // c is not a function -
Operadores • Aritméticos: +, -, *, /, %, ++, --;
• Atribuição: =, +=, -=, *=, /=, %=; • Comparação: =, !=, >, >=, <, <=, ===, !==; • Lógicos: !, ||, &&, ? :; • Bitwise: &, |, ^, <<, >>, >>>, ~; • String: =, +, +=. -
Condições & Loops if (expressão) { // instrução } else
if (expressão) { // instrução } else { // instrução } -
Condições & Loops switch (expressao) { case algum valor: //
instrução break case outro valor: // instrução break default: // instrução break } -
Condições & Loops while (condicao) { // instrução } do
{ // instrução } while (condição) -
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. -
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 !==. -
Number if (0.1 + 0.2 == 0.3) { console.log('0.3!') }
else { console.log('ahn?') } -
String • Aceita tanto ' quanto ": 'foo' === "foo";
• UTF-16: '日本語'. -
null vs undefined • null representa vazio; • undefined representa
indefinido. var a; // a === undefined -
Objetos JavaScript são como um hash var fulano = {
nome: 'fulano', idade: 30 } -
Objetos podem ser aninhados var compra = { item: 'churros',
quantidade: 1, cliente: { nome: 'fulano', idade: 30 } } -
Propriedades podem conter espaços var fulano = { nome: 'fulano',
idade: 30, 'data de nascimento': new Date(1985, 0, 1) } -
Propriedades fulano.nome // acessando fulano['nome'] // acessando de outra maneira
fulano.altura = 175 // criando uma nova propriedade delete fulano.idade // removendo uma propriedade -
Iterando sobre propriedades for (var prop in fulano) { //
prop é a chave // fulano[prop] é o valor } -
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) -
JavaScript Object Notation { "id": 123, "nome": "churros", "preço": 2.75,
"tags": [ "comidas", "doces" ] } -
Serialização var str = JSON.stringify(obj) // serialização var obj =
JSON.parse(str) // deserialização -
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. -
Funções // sempre retornam algum valor // undefined no exemplo
abaixo function hello () { console.log('Hello world!') } -
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. -
Closure function lembrar (mensagem) { var lembrete = 'Lembrete: '
+ mensagem setInterval(function () { console.log(lembrete) }, 5000) } lembrar('o JavaScript "guardou" a variável local!') -
arguments function ImprimoQualquerCoisa () { for (var i = 0;
i < arguments.length; ++i) { console.log(arguments[i]) } } ImprimoQualquerCoisa() ImprimoQualquerCoisa(1, 2, 3) ImprimoQualquerCoisa(undefined) -
Inicializando arrays var arrayVazio = [ ] var arrayComElementos =
[ 1, 2, 'três' ] -
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 -
for for (var i = 0; i < nomes.length; ++i)
{ console.log(nomes[i]) } -
forEach // nome é o mesmo que array[indice] nomes.forEach(function (nome,
indice, array) { console.log(nome) }) -
every function nomePreenchido (nome) { return !!nome } // true
se todos nomes nomes.every(nomePreenchido) // estiverem preenchidos -
map function emMaiusculo (nome) { return nome.toUpperCase() } nomes.map(emMaiusculo) //
retorna os nomes em maiúsculo -
reduce function soma (a, b) { return a + b
} precos.reduce(soma) // total dos preços -
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.