Baixe o app para aproveitar ainda mais
Prévia do material em texto
Desenvolvimento de Software para WEB Fundamentos de Javascript Prof. Regis Pires Magalhães regispires@lia.ufc.br Histórico • Criada por Brendan Eich em 1995 para a Netscape. • Originalmente chamado LiveScript. • Alteração do nome por decisão de marketing apoiada na popularidade da linguagem Java tem sido uma fonte de mal entendidos. • Adaptado pela Microsoft como JScript para IE 3 em 1996. • Padronizado como ECMAScript em 1997. • Variação incluída no Flash como ActionScript. • Atualizada para ECMAScript 3ª Edição em 1998. Comentários // this is a comment /* this is a multi-line or block comment */ Usando na página HTML <script type="text/javascript"> // <![CDATA[ ... JavaScript code goes here ... // ]]> </script> Externalizando: <script type="text/javascript" src="my_script.js"/> Tipos • Number • String • Boolean • Object ▫ Function ▫ Array ▫ Date ▫ RegExp • Null • Undefined Números • Não há inteiro. ▫ 0.1 + 0.2 = 0.30000000000000004 • Operações: ▫ 3 + 5.3 ▫ 28 % 6 • Objeto Math ▫ Math.sin(3.5); ▫ d = Math.PI * r * r; parseInt (e parseFloat) • Conversão de string para número (defina a base): > parseInt("123", 10) 123 > parseInt("010", 10) 10 > parseInt("11", 2) 3 NaN e Infinity > parseInt("hello", 10) NaN > NaN + 5 NaN > isNaN(NaN) true > 1 / 0 Infinity > -1 / 0 -Infinity Strings > "hello".length 5 • Strings são objetos: > "hello".charAt(0) h > "hello, world".replace("hello", "goodbye") goodbye, world > "hello".toUpperCase() HELLO Strings Null e undefined • null = deliberadamente sem valor • undefined = ainda sem valor atribuído ▫ Variáveis declaradas, mas não inicializadas ▫ Membros Objeto/Array que não existem Boolean • true ou false • False: 0, "", NaN, null, undefined • Tudo mais é true • Operações: &&, || e ! • Conversão para equivalente booleano: > !!"" false > !!234 true Variáveis • Declaradas com a palavra chave var: var a; var name = "simon"; • Declarar sem atribuir valor: undefined • Se esquecer a palavra var, a variável é global. Não faça isso, por favor. Operadores • Numéricos: +, -, *, / e % • Atribuição: =, +=, -=, *=, /=, %= • Incremento/decremento: a++, ++a, b--, --b • Concatenação de string: > "hello" + " world" hello world • Coerção de tipos: > "3" + 4 + 5 345 > 3 + 4 + "5" 75 • Adicionar uma string vazia a alguma coisa, converte tudo para string. Comparação • Para números e strings: <, >, <= e >= • Igualdade: == e != > "dog" == "dog" true > 1 == true true • === e !== evitam coerção de tipos > 1 === true false > true === true true typeof Estruturas de Controle - if var name = "kittens"; if (name == "puppies") { name += "!"; } else if (name == "kittens") { name += "!!"; } else { name = "!" + name; } name == "kittens!!" Estruturas de Controle – while e do-while while (true) { // an infinite loop! } do { var input = get_input(); } while (inputIsNotValid(input)) Estruturas de Controle – for for (var i = 0; i < 5; i++) { // Will execute 5 times } Estruturas de Controle – switch switch(action) { case 'draw': drawit(); break; case 'eat': eatit(); break; default: donothing(); } Estruturas de Controle – switch • Expressões são permitidas • Comparações usam === switch(1 + 3): case 2 + 2: yay(); break; default: neverhappens(); } Curto circuito lógico • && e || só executam o segundo operando, dependendo do resultado do primeiro. • Útil para checagem de objetos antes de acessar seus atributos: var name = o && o.getName(); • Atribuição de valor default: var name = otherName || "default"; Operador ternário var allowed = (age > 18) ? "yes" : "no"; Exceções Objetos • Simples pares nome-valor, como: ▫ Dicionários em Python ▫ Hashes em Perl e Ruby ▫ Hash tables em C e C++ ▫ HashMaps em Java ▫ Arrays associativos em PHP • Muito comuns, estrutura de dados versátil. • Nome é uma string; valor pode ser qualquer coisa. Criação de Objetos var obj = new Object(); ou: var obj = {}; • Equivalentes. A segunda opção chama-se sintaxe literal de objeto e é mais conveniente. Acesso a atributos obj.name = "Simon" var name = obj.name; ou: obj["name"] = "Simon"; var name = obj["name"]; • Equivalentes. • O segundo usa strings, podendo ser decidido em tempo de execução e usado para palavras reservadas. Sintaxe Literal de Objetos var obj = { name: "Carrot", "for": "Max", details: { color: "orange", size: 12 } } Para acessar: > obj.details.color orange > obj["details"]["size"] 12 for (var attr in obj) • Pode-se iterar pelas chaves de um objeto: var obj = { 'name': 'Simon', 'age': 25 }; for (var attr in obj) { print (attr + ' = ' + obj[attr]); } Arrays • Tipo especial de objeto: as chaves são números e não strings. • Sintaxe [ ]: > var a = new Array(); > a[0] = "dog"; > a[1] = "cat"; > a[2] = "hen"; > a.length 3 Arrays – sintaxe literal > var a = ["dog", "cat", "hen"]; > a.length 3 Array.length > var a = ["dog", "cat", "hen"]; > a[100] = "fox"; > a.length 101 > typeof(a[90])] undefined Append seguro: a[a.length] = item; Iteração em Array for (var i = 0; i < a.length; i++) { // Do something with a[i] } Mais eficiente: for (var i = 0, j = a.length; i < j; i++) { // Do something with a[i] } Facilidade de uso sem elementos 'falsos': for (var i = 0, item; item = a[i]; i++) { // Do something with item } Arrays Funções function add(x, y) { var total = x + y; return total; } • Se nada for explicitamente retornado, o valor de retorno é undefined. Passagem de parâmetros: > add() Nan // You can't perform addition on undefined > add(2, 3, 4) • 5 // added the first two; 4 was ignored Parâmetros function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum; } > add(2, 3, 4, 5) 14 Funções anônimas var avg = function() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; } return sum / arguments.length; } Funções e Objetos function makePerson(first, last) { return { first: first, last: last } } function personFullName(person) { return person.first + ' ' + person.last; } function personFullNameReversed(person) { return person.last + ', ' + person.first } > s = makePerson("Simon", "Willison"); > personFullName(s) Simon Willison > personFullNameReversed(s) Willison, Simon Métodos function makePerson(first, last) { return { first: first, last: last, fullName: function() { return this.first + ' ' + this.last; }, fullNameReversed: function() { return this.last + ', ' + this.first; }} } > s = makePerson("Simon", "Willison") > s.fullName() Simon Willison > s.fullNameReversed() Willison, Simon Construtores Eventos comuns Árvore de Objetos Browser Object Model Manipulação de Objetos • document.layers['myLayer']; • document.all['myLayer']; DOM – Documento Object Model <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Sample XHTML</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Language" content="en-us" /> </head> <body> <h1>This is a heading, level 1</h1> <p>This is a paragraph of text with a <a href="/path/to/another/page.html">link</a>.</p> <ul> <li>This is a list item</li> <li>This is another</li> <li>And another</li> </ul> </body> </html> Árvore de documento Coleção de Nós • Elementos • Atributos • Textos Elemento p DOM <div id="content"> <h1>This is a heading</h1> <p>This is a paragraph.</p> <h2>This is another heading</h2> <p>This is another paragraph.</p> <p>Yet another paragraph.</p> </div> var the_div = document.getElementById( 'content' ); var h2s = the_div.getElementsByTagName( 'h2' ) var the_h2 = h2s[0]; var everything = document.getElementsByTagName( '*' ); get/set attribute var href = document.getElementById( 'easy' ).getAttribute( 'href' ); var link = document.getElementById( 'easy' ); link.setAttribute( 'href', 'http://www.easy- designs.net/index.php' ); link.setAttribute( 'title', 'The Easy Designs, LLC homepage' ); Métodos var new_div = document.createElement( 'div' ); var text = document.createTextNode( 'This is a new div' ); new_div.appendChild( text ); new_div.appendChild( document.createTextNode( 'This is a new div' ) ); var body = document.getElementsByTagName( 'body' )[0]; body.insertBefore( new_div, body.firstChild ); body.replaceChild( new_div, body.firstChild ); div.removeChild( div.firstChild ); Métodos var ul = document.createElement( 'ul' ); var li = document.createElement( 'li' ); li.className = 'check'; for( var i=0; i < 5; i++ ){ var new_li = li.cloneNode( true ); new_li.appendChild( document.createTextNode( 'list item ' + ( i + 1 ) ) ); ul.appendChild( new_li ); } Manipulando Estilos var div = document.getElementById( 'content' ); div.setAttribute( 'style', 'color: #f00; font-weight: bold;' ); div.style.color = '#f00'; div.style.fontWeight = 'bold'; Referências e Links importantes • Vídeos da Universidade XTI • www.w3schools.com • www.gimp.org • Apostila da K19 - Desenvolvimento Web com HTML, CSS e Javascript. • RODRIGUES, Andréa. Desenvolvimento para Internet. 1ª Edição, Editora do Livro Técnico, 2010. Referências e Links importantes • A (Re)-Introduction to JavaScript ▫ Simon Willison - http://simonwillison.net/ ▫ http://simon.incutio.com/slides/2006/etech/javascript/js -tutorial.001.html ▫ http://simon.incutio.com/slides/2006/etech/javascript/js -reintroduction-notes.html • ROBBINS, Jennifer. Web Design in a Nutshell. O'Reilly. 3ª Ed .2006. • Argonavis ▫ www.argonavis.com.br • Netscape Javascript Authoring Guide
Compartilhar