<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-34235652</id><updated>2011-12-14T01:56:18.708-02:00</updated><title type='text'>JavaScript Developer</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>8</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-34235652.post-3623267902155977105</id><published>2008-10-08T23:34:00.003-03:00</published><updated>2008-10-08T23:37:41.025-03:00</updated><title type='text'>Novo blog</title><content type='html'>Ola amigos, essa postagem é apenas na esperança que alguém ainda tenha esse blog marcado em algum lugar (se é que isso é possível), bom, lancei hoje meu novo blog, dessa vez sobre assuntos de desenvolvimento em geral, e iniciei com um post sobre porque devemos utilizar UTF-8.&lt;br /&gt;&lt;br /&gt;Como esse blog e generalista terei mais ideias para postar e pretendo postar com mais frequência, quem gostava desse blog deve gostar do novo também ;)&lt;br /&gt;&lt;br /&gt;Entao acessem: &lt;a href="http://wilker-dev.blogspot.com/"&gt;http://wilker-dev.blogspot.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Vlw!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-3623267902155977105?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/3623267902155977105/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=3623267902155977105&amp;isPopup=true' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/3623267902155977105'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/3623267902155977105'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2008/10/novo-blog.html' title='Novo blog'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-116162497602437999</id><published>2006-10-23T14:33:00.000-03:00</published><updated>2007-10-29T20:52:35.090-02:00</updated><title type='text'>DOM - Básico</title><content type='html'>E ae galera! Pow, to atrasadão com vocês... mal ae, tava sem tempo no trabalho esses dias, mas hoje vamos voltar aos estudos :)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;O que raios é DOM?&lt;/b&gt;&lt;br /&gt;DOM é a sigla para Document Object Model (Modelo de Objecto de Documento), ele é uma API para ler e escrever XML (é a padrão da W3C e tem sua implementação na maioria das linguagens atuais). Com o DOM é possivel localizar elementos dentro de um XML, alterar atributos, criar novos elementos e outros recursos.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;DOM em JavaScript&lt;/b&gt;&lt;br /&gt;No JavaScript particularmente, o DOM é de vital importância, enquanto em outras linguages você usa o DOM para realmente ler, escrever e salvar documentos XML, no JavaScript ele é usado para mudar a página dinâmicamente. Você deve saber que a página web é mostrada na tela após o conteudo HTML (ou XHTML) ser carregado, a grande jogava do DOM no JavaScript é que com ele você muda os atributos do HTML atual, e automaticamente a exibição é atualizada! Se você associar isso ao fato de conseguir alterar também o CSS dos elementos, os efeitos que podem ser gerados estão além do que muita gente pensa quanto a capacidade de sites. Essa arte de mexer com elementos usando DOM no JavaScript é chamada DHTML, quando você ver esse nome na net, não se assuste, DHTML não é uma linguagem, é apenas o uso do JavaScript para mexer com HTML ;)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Começando com DOM&lt;/b&gt;&lt;br /&gt;Bom, vamos passar a escrever agora todo o HTML no código, pois como vamos mexer no HTML, não da pra ter apenas código JavaScript (eu me refiro ao usar o esqueleto de código que eu passei no primeiro artigo, e realmente, é possivel fazer DHTML sem ter código HTML prévio, mas vamos deixar isso para depois).&lt;br /&gt;&lt;br /&gt;Nosso documento HTML que será usado inicialmente (use ele, o resto iremos colocar somente na tag script):&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&amp;lt;html&amp;gt;&lt;br /&gt;&amp;lt;head&amp;gt;&lt;br /&gt; &amp;lt;title&amp;gt; :: JavaScript Developer - Aprendendo DOM :: &amp;lt;/title&amp;gt;&lt;br /&gt; &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;  //o codigo vira aqui&lt;br /&gt; &amp;lt;/script&amp;gt;&lt;br /&gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&amp;lt;body&amp;gt;&lt;br /&gt;&amp;lt;form id="meuFormulario"&amp;gt;&lt;br /&gt;&amp;lt;table&amp;gt;&lt;br /&gt; &amp;lt;tr&amp;gt;&lt;br /&gt;  &amp;lt;td valign="top"&amp;gt;Linguagens que programa:&amp;lt;/td&amp;gt;&lt;br /&gt;  &amp;lt;td&amp;gt;&lt;br /&gt;   &amp;lt;div id="camposCheck"&amp;gt;&lt;br /&gt;    &amp;lt;input type="checkbox" name="linguagens[]" /&amp;gt; PHP&amp;lt;br /&amp;gt;&lt;br /&gt;    &amp;lt;input type="checkbox" name="linguagens[]" /&amp;gt; JavaScript&amp;lt;br /&amp;gt;&lt;br /&gt;    &amp;lt;input type="checkbox" name="linguagens[]" /&amp;gt; C++&amp;lt;br /&amp;gt;&lt;br /&gt;    &amp;lt;input type="checkbox" name="linguagens[]" /&amp;gt; Java&amp;lt;br /&amp;gt;&lt;br /&gt;    &amp;lt;input type="checkbox" name="linguagens[]" /&amp;gt; CSS&amp;lt;br /&amp;gt;&lt;br /&gt;   &amp;lt;/div&amp;gt;&lt;br /&gt;   &amp;lt;div id="fastCheckDiv" style="display: none;"&amp;gt;&lt;br /&gt;    &amp;lt;a href="#" id="marcaTodosLink"&amp;gt;Marcar Todos&amp;lt;/a&amp;gt;&lt;br /&gt;    &amp;lt;a href="#" id="desmarcaTodosLink"&amp;gt;Desmarcar Todos&amp;lt;/a&amp;gt;&lt;br /&gt;   &amp;lt;/div&amp;gt;&lt;br /&gt;  &amp;lt;/td&amp;gt;&lt;br /&gt; &amp;lt;/tr&amp;gt;&lt;br /&gt; &amp;lt;tr&amp;gt;&lt;br /&gt;  &amp;lt;td&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt;  &amp;lt;td&amp;gt;&amp;lt;button type="submit"&amp;gt;Enviar Formulário&amp;lt;/button&amp;gt;&amp;lt;/td&amp;gt;&lt;br /&gt; &amp;lt;/tr&amp;gt;&lt;br /&gt;&amp;lt;/table&amp;gt;&lt;br /&gt;&amp;lt;/form&amp;gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Iremos comecar com o mais simples, os formulários, mas antes eu gostaria de expor um conceito muito bem aceito hoje em dia, que é o conceito do JavaScript "não obstrutivo".&lt;br /&gt;&lt;br /&gt;&lt;b&gt;JavaScript não obstrutivo&lt;/b&gt;&lt;br /&gt;O que seria isso? É simplesmente fazer o uso do JavaScript sem faze-lo obrigatório para visualização, fazendo com que dessa forma, o JavaScript seja apenas um adicional, e não fundamental. E como fazer isso? A primeira coisa a ser feita, é deixar tudo funcionando sem JavaScript, como vocês podem ver, o formulário do código acima não tem nada de JavaScript, mas se clicar-mos no botão de enviar, o formulário vai ser enviado sem nenhum problema, entao ja temos a solução no HTML, e agora iremos apenas incrementar mais interatividade. No JavaScript não obstrutivo nós não colocamos código JavaScript no meio do HTML, no lugar de fazer isso apenas nomeamos elementos com ID, e depois os pegamos usando o DOM!&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Voltando ao formulario&lt;/b&gt;&lt;br /&gt;OK, nesse formulário iremos incrementar uma função pra marcar e desmarcar todos os checkbox mais facilmente. obs: eu ia fazer uma validação com um campo de nome também, mas isso usuária muito código, e parar um evento de forma não obstrutiva não é tão simples, entao prefiro deixar isso para quando formos falar de eventos em futuros artigos.&lt;br /&gt;&lt;br /&gt;Como sempre, primeiro o código, depois explicações ;)&lt;br /&gt;&lt;br /&gt;&lt;code&gt;function $(obj) {&lt;br /&gt; return document.getElementById(obj);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function marcaBoxes(marcar) {&lt;br /&gt; var boxesContainer = $('camposCheckDiv');&lt;br /&gt; var childs = boxesContainer.childNodes;&lt;br /&gt; &lt;br /&gt; for(var i = 0; i &amp;lt; childs.length; i++) {&lt;br /&gt;  var node = childs[i];&lt;br /&gt;  &lt;br /&gt;  if(node.nodeType == 1 &amp;&amp; node.tagName == "INPUT")&lt;br /&gt;   node.checked = marcar;&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;window.onload = function() {&lt;br /&gt; var marcaTudoObj = $('marcaTodosLink');&lt;br /&gt; var desmarcaTudoObj = $('desmarcaTodosLink');&lt;br /&gt; var fastCheckObj = $('fastCheckDiv');&lt;br /&gt; &lt;br /&gt; marcaTudoObj.onclick = function() {&lt;br /&gt;  marcaBoxes(true);&lt;br /&gt; };&lt;br /&gt; &lt;br /&gt; desmarcaTudoObj.onclick = function() {&lt;br /&gt;  marcaBoxes(false);&lt;br /&gt; };&lt;br /&gt; &lt;br /&gt; fastCheckObj.style.display = '';&lt;br /&gt;};&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Vamos com calma, esse script tem várias coisas novas, vamos pelo começo:&lt;br /&gt;&lt;br /&gt;A função &lt;b&gt;$(obj)&lt;/b&gt; -&gt; eu já disse antes que para mexer com os elementos de forma não obstrutiva, devemos colocar ID neles, para pegar isso com o DOM, mas eu ainda não tinha falado como fazer isso. Primeiro de tudo, a variável pré-definida &lt;b&gt;document&lt;/b&gt; é o objeto principal do DOM, vamos falar mais sobre ela depois, por enquanto, saibamos que ela tem um método chamado &lt;b&gt;getElementById()&lt;/b&gt;, e como claramente o nome diz, esse método serve justamente para pegar a referência para em elemento dentro do HTML atual. O que a função $() faz é apenas servir de atalho para &lt;b&gt;document.getElementById()&lt;/b&gt;, porque convenhamos, escrever &lt;b&gt;document.getElementById()&lt;/b&gt; o tempo todo é uma me***. Futuramente vamos ver como deixar essa função ainda melhor.&lt;br /&gt;&lt;br /&gt;A função &lt;b&gt;marcaBoxes(marcar)&lt;/b&gt; -&gt; essa é a função principal para o nosso sistema, é ela que vai lá e marca / desmarca os checkbox, o parêmetro &lt;b&gt;marcar&lt;/b&gt; serve para indicar se ela vai marcar ou desmarcar os checkbox. Vamos estuda-la passo a passo:&lt;br /&gt;&lt;br /&gt;var boxesContainer = $('camposCheckDiv'); =&gt; essa linha pega o elemento DIV que está contendo os nossos checkbox, precisamos de algo que circunde nosso checkbox para poder pega-los de forma dinâmica e eficiente&lt;br /&gt;&lt;br /&gt;var childs = boxesContainer.childNodes; =&gt; essa é legal, todos os objetos HTML tem uma propriedade chamada &lt;b&gt;childNodes&lt;/b&gt;, o childNodes é um array contendo todos as referencias para os elementos dentro do dele. Ou seja, como nossos checkboxes estão dentro de &lt;b&gt;boxesContainer&lt;/b&gt;, então entre os childNodes do &lt;b&gt;boxesContainer&lt;/b&gt; estão todos os nossos checkboxes que devem ser marcados / desmarcados&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; childs.length; i++) { =&gt; iniciamos nosso loop pelos childNodes&lt;br /&gt;&lt;br /&gt;var node = childs[i]; =&gt; colocamos um nó atual numa variável, apenas para ficar mais claro&lt;br /&gt;&lt;br /&gt;if(node.nodeType == 1 &amp;&amp; node.tagName == "INPUT") =&gt; essa linha aqui é importante, primeiro verificamos se o nó é um elemento realmente, os elementos HTML (aqueles entre tags) são representados pelo valor 1, mas existem outros também:&lt;br /&gt;&lt;br /&gt;1 - elemento HTML, exemplo: &amp;lt;p&amp;gt;...&amp;lt;/p&amp;gt;&lt;br /&gt;2 - atributo, exemplo: align="center"&lt;br /&gt;3 - texto, exemplo: conteudo de alguma coisa&lt;br /&gt;8 - comentário, exemplo: &amp;lt;!-- comentario html --&amp;gt;&lt;br /&gt;9 - document, é o nó principal do XML, exemplo: &amp;lt;html&amp;gt;&lt;br /&gt;10 - definição do documento, exemplo: &amp;lt;!DOCTYPE HTML PUBLIC "-//W3C //DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;&lt;br /&gt;&lt;br /&gt;pela lista podemos ver que o único em que estamos interessados é o número 1. O segundo item verifica se o nosso elemento é um input (lembre-se, também temos uns &amp;lt;br /&amp;gt; no meio), um detalhe, a propriedade &lt;b&gt;tagName&lt;/b&gt; sempre fica em maiúsculo, independende de como vocês a escreveu no HTML.&lt;br /&gt;&lt;br /&gt;node.checked = marcar; -&gt; finalmente, após tudo estamos marcado ou desmarcando o checkbox (de acordo com o parâmetro passado), a propriedade &lt;b&gt;checked&lt;/b&gt; pertence apenas a radios e checkboxes, ela indica se ele esta ou não marcado, e pode ser usada para definir também (como nós fizemos).&lt;br /&gt;&lt;br /&gt;Ufa, terminamos a função principal, vamos a parte do código que faz a nossa mágica da não obstrução:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;window.onload = function() {&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Colamos o codigo dentro dessa função por um motivo simples, nós vamos mexer com o HTML do site, se tentarmos fazer isso antes do documento ser carregado vai dar erro (pois os elementos ainda não vão existir). Por hora, apenas saiba que window.onload é o evento que dispara quando a página é carregada.&lt;br /&gt;&lt;br /&gt;&lt;code&gt; var marcaTudoObj = $('marcaTodosLink');&lt;br /&gt; var desmarcaTudoObj = $('desmarcaTodosLink');&lt;br /&gt; var fastCheckObj = $('fastCheckDiv');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Nessas linhas pegamos as referências para os elementos HTML.&lt;br /&gt;&lt;br /&gt;&lt;code&gt; marcaTudoObj.onclick = function() {&lt;br /&gt;  marcaBoxes(true);&lt;br /&gt; };&lt;br /&gt; &lt;br /&gt; desmarcaTudoObj.onclick = function() {&lt;br /&gt;  marcaBoxes(false);&lt;br /&gt; };&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Agora colocamos os eventos, estamos dizendo que quando clicar, é para executar a função (que vai logo em seguida). Essa com certeza não é a melhor maneira para colocar eventos nos objetos, mas é a mais simples.&lt;br /&gt;&lt;br /&gt;&lt;code&gt; fastCheckObj.style.display = '';&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;E finalmente, nós fazemos os links ficarem visíveis alterando o css dele (vejam como é simples alterar um css, apenas digita-se .style, depois .propriedade e altera). O motivo de ter deixado os links invisíveis, pensem bem, esses links só funcionam se o JavaScript estiver ativado, então, se o JavaScript estiver desativado eles irão permanecer invisíveis, dessa forma o clinte não vai tentar clicar numa coisa que não faz nada.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Mais explicações&lt;/b&gt;&lt;br /&gt;Talvez você tenha entendido, talvez não, mas o DOM usa uma estrutura de árvore para guardar os elementos, se você já estudou e sabe oque é isso, ótimo, se não, pense no windows explorer, quando vemos as pastas à esquerda, aquilo é uma estrutura de árvore, cada "nó" pai pode ter varios "nós" filhos, e assim sucessivamente, do mesmo jeito que uma árvore tem galhos, e galhos sobre galhos... No XML temos o nó principal (no HTML seria a propria tag &amp;lt;html&amp;gt;), e esse nó tem varios filhos (&amp;lt;head&amp;gt; &amp;lt;body&amp;gt;), que pode sua vez tem mais varios... Usando esse pensamentos podemos percorrer o documento do jeito que quizermos. Vou colocar os principais atributos usados:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;objeto.childNodes&lt;/b&gt; - coleção com os nós filhos&lt;br /&gt;&lt;b&gt;objeto.parentNode&lt;/b&gt; - nó pai (o nó em qual ele está agrupado)&lt;br /&gt;&lt;b&gt;objeto.nextSibling&lt;/b&gt; - o próximo nó (ainda dentro do mesmo pai)&lt;br /&gt;&lt;b&gt;objeto.previousSibling&lt;/b&gt; - nó anterior (dentro do mesmo pai)&lt;br /&gt;&lt;b&gt;objeto.tagName&lt;/b&gt; - nome da tag&lt;br /&gt;&lt;b&gt;objeto.nodeName&lt;/b&gt; - nome da tag (mesma coisa que o anterior)&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Com isso você pode "navegar" a vontade pelo documento a partir de qualquer lugar. Existe uma coisa do DOM chamada XPath, com ele você facilmente localiza nodes no documento, eu sinceramente ainda não estudei o XPath no JavaScript, mas sei que ele existe, qualquer dia desses eu posto só sobre isso ;)&lt;br /&gt;&lt;br /&gt;Por hoje ficamos por aqui, no próximo artigo vou falar sobre DHTML, vamos fazer alguns efeitos no site. Como sempre, aquela referência esperta (essa é meio grande XD) dos objetos html em geral:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;Generic HTML Element Object (Document Object)&lt;/b&gt;&lt;br /&gt;Generic (X)HTML elements have the form described here. This list of properties, methods, and event handlers are common to almost all (X)HTML element objects and are, in fact, the only properties, methods, and event handlers defined for a large number of very basic elements, such as &amp;lt;b&amp;gt;, &amp;lt;i&amp;gt;, and &amp;lt;u&amp;gt;. Each of these objects corresponds to an occurrence of an (X)HTML element on the page. Access to one of these objects is achieved through standard DOM methods like document.getElementById().&lt;br /&gt;&lt;br /&gt;&lt;b&gt; Note&lt;/b&gt;  Some properties do not have a well-defined meaning for particular objects, even though the properties may be defined for them. For example, blurring an &amp;lt;hr&amp;gt; tag is interesting given that it is difficult to focus the object in general Web use. &lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;accessKey&lt;/b&gt; Single character string indicating the hotkey that gives the element focus. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;all[]&lt;/b&gt; Collection of elements enclosed by the object. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;align&lt;/b&gt; String specifying the alignment of the element, for example, "left". This property is defined only for display elements such as b, big, cite, and so on. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;attributes[]&lt;/b&gt; Collection of read-only attributes for the element. (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;begin&lt;/b&gt; Sets or retrieves delay before timeline begins playing the element. See MSDN. (IE5.5+, SMIL)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;behaviorUrns[]&lt;/b&gt; Collection of DHTML Behaviors attached to the node. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;canHaveChildren&lt;/b&gt; Read-only Boolean value indicating whether the element can have child nodes. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;canHaveHTML&lt;/b&gt; Read-only Boolean indicating whether the element can enclose HTML markup. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;childNodes[]&lt;/b&gt; Read-only collection of child nodes of the object. (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;children[]&lt;/b&gt; Read-only collection of child nodes. This is IE’s pre-DOM equivalent of childNodes[]. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;className&lt;/b&gt; String holding value of the CSS class(es) the element belongs to. (IE4+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;clientHeight&lt;/b&gt; Read-only numeric value indicating the height of the element’s content area in pixels. (IE4+) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;clientLeft&lt;/b&gt; Read-only numeric value indicating the difference between the offsetLeft property and the beginning of the element’s content area, in pixels. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;clientTop&lt;/b&gt; Read-only numeric value indicating the difference between the offsetTop property and the beginning of the element’s content area, in pixels. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;clientWidth&lt;/b&gt; Read-only numeric value indicating the width of the element’s content area in pixels. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;contentEditable&lt;/b&gt; String determining whether the element’s content is editable. Values are "inherit", "true", or "false". A value of "inherit" means that it will inherit the contentEditable property of its parent (this value is the default). This property is useful for making table data cells editable. Elements with disabled set to true are not editable, no matter what value this property has. Corresponds to the contenteditable attribute. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;currentStyle&lt;/b&gt; Read-only reference to the Style object reflecting all styles applied to the element, including global (default) style. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;dir&lt;/b&gt; String holding the text direction of text enclosed by the element. If set, its value is either "ltr" (left to right) or "rtl" (right to left). (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;disabled&lt;/b&gt; Boolean indicating whether the element is disabled (grayed out). (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;document&lt;/b&gt; An undocumented reference to the Document in which the element is contained. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;filters[]&lt;/b&gt; Collection of Microsoft CSS Filters applied to the element. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;firstChild&lt;/b&gt; Read-only reference to the first child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;hasMedia&lt;/b&gt; Read-only Boolean indicating whether the element is an HTML+TIME media element. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;hideFocus&lt;/b&gt; Boolean indicating whether the object gives a visible cue when it receives focus. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;id&lt;/b&gt; String holding the unique alphanumeric identifier for the element. Commonly assigned using the id HTML attribute and used as the target for getElementById(). This unique identifier is not only important for scripting, but also for binding of CSS. (IE4+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;innerHTML&lt;/b&gt; String holding the HTML content enclosed within the element’s tags. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;innerText&lt;/b&gt; String holding the text enclosed by the element’s tags. This text is not interpreted as HTML, so setting it to a value like "&amp;lt;b&amp;gt;Important&amp;lt;/b&amp;gt;" will result in "&amp;lt;b&amp;gt;Important&amp;lt;/b&amp;gt;" being displayed, rather than "Important" with boldfaced font. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isContentEditable&lt;/b&gt; Read-only Boolean indicating if the user can edit the element’s contents. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isDisabled&lt;/b&gt; Read-only Boolean indicating if the user can interact with the object. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isTextEdit&lt;/b&gt; Read-only Boolean indicating if a TextRange object can be created using the object. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lang&lt;/b&gt; String holding language code for the content the element encloses. Corresponds to the lang HTML attribute. For a full list of valid values, see RFC 1766 (http://www.ietf.org/rfc/rfc1766.txt?number=1766), which describes language codes and their formats. (IE4+, MOZ/N6+, DOM1) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;language&lt;/b&gt; String indicating the scripting language in use. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lastChild&lt;/b&gt; Read-only reference to the last child node of the element, if one exists (null otherwise). (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;localName&lt;/b&gt; Read-only string indicating the "local" XML name for the object. (MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;namespaceURI&lt;/b&gt; Read-only string indicating the XML Namespace URI for the object. (MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;nextSibling&lt;/b&gt; Read-only reference to next sibling of the node, for example, if its parent has multiple children. (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;nodeName&lt;/b&gt; Read-only string containing name of the node, the name of the tag to which the object corresponds, for example, "H1". (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;nodeType&lt;/b&gt; Read-only number holding the DOM defined node type. For example, element nodes have node type 1. A list of the common node types can be found in the following table. (IE5+, MOZ/N6+, DOM1) [tabela 1]&lt;br /&gt;&lt;br /&gt;&lt;b&gt;nodeValue&lt;/b&gt; String containing value within the node (or null if no value). (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;offsetHeight&lt;/b&gt; Read-only numeric value indicating the height of the element in pixels. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;offsetLeft&lt;/b&gt; Read-only numeric value indicating the pixel offset of the left edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;offsetParent&lt;/b&gt; Read-only reference to the object relative to which the offsetHeight/Width/Left/Top is calculated. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;offsetTop&lt;/b&gt; Read-only numeric value indicating the pixel offset of the top edge of the element, relative to its offsetParent. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;offsetWidth&lt;/b&gt; Read-only numeric value indicating the width of the element in pixels. (IE4+, MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;outerHTML&lt;/b&gt; String holding the HTML content enclosed within (and including) the element’s tags. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;outerText&lt;/b&gt; String holding the text enclosed by (and including) the element’s tags. (IE4+) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;ownerDocument&lt;/b&gt; Read-only reference to the Document in which the element is contained. (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parentElement&lt;/b&gt; Reference to the node’s parent. This is IE’s pre-DOM equivalent of parentNode. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parentNode&lt;/b&gt; Read-only reference to the parent of the object (or null if none exists). (IE4+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parentTextEditv&lt;/b&gt; Read-only reference to the innermost container element outside of the current object that is capable of creating a TextRange containing the current element. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prefixv&lt;/b&gt; Read-only string containing the "prefix" XML name for the object. (MOZ/N6+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;previousSibling&lt;/b&gt; Read-only reference to previous sibling of the node, for example, if its parent node has multiple children. (IE5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;readyState&lt;/b&gt; Read-only string containing the current state of the object. Values include "uninitialized", "loading", "loaded", "interactive" (not finished loading but able to respond to user actions), and "complete". Objects progress through each of these states until they have completed loading, though some objects may skip some intermediate steps (for example, pass from "uninitialized" directly to "complete"). This property is very useful in determining whether an element has completed loading. However, you should always make sure the object exists in the Document before attempting to read this property (otherwise, a runtime error will be thrown because you would be attempting to read a property of an object not yet defined). Note that an &amp;lt;object&amp;gt;s readyState is given by the integers 0 through 4 (with the same meaning). (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;recordNumber&lt;/b&gt; Read-only numeric value indicating the record number of the data set from which the element was generated. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;runtimeStyle&lt;/b&gt; Reference to the Style object that reflects the current (runtime) style characteristics of the element. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;scopeName&lt;/b&gt; Read-only string containing the XML scope for the object. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;scrollHeight&lt;/b&gt; Numeric read-only value indicating the total height in pixels of the element’s content area, no matter how much is displayed on screen. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;scrollLeft&lt;/b&gt; Numeric value indicating the distance in pixels from the left edge of the object to the leftmost edge of the object that is currently displayed. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;scrollTop&lt;/b&gt; Numeric value indicating the distance in pixels from the top edge of the object to the topmost edge that is currently displayed. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;scrollWidth&lt;/b&gt; Numeric read-only value indicating the total width in pixels of the object’s content area, no matter how much is displayed on screen. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;sourceIndex&lt;/b&gt; Read-only number indicating the index of the element in the document.all[] collection. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;style&lt;/b&gt; Reference to the inline Style object for the element. (IE4+, N4+, DOM2)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;syncMaster&lt;/b&gt; Specifies whether time container must synchronize with the element. See MSDN. (IE5.5+, SMIL)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;tabIndex&lt;/b&gt; Numeric value indicating the tab order for the object. Elements with positive values for this property are tabbed to in order of increasing tabIndex (before any others). Elements with zero for this property (the default) are tabbed to in the order they occur in the document source. Elements with negative values are not tabbed to at all. (IE4+) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;tagName&lt;/b&gt; String containing the name of the tag to which the object corresponds, for example, "H1." (IE5.5+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;tagUrn&lt;/b&gt; String containing the URN of the XML Namespace for the object. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;timeContainer&lt;/b&gt; Sets or retrieves the type of timeline associated with the element. (IE5.5+, SMIL)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;title&lt;/b&gt; String containing advisory text for the element. (IE4+, MOZ/N6+, DOM1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;uniqueID&lt;/b&gt; An auto-generated read-only unique id for this element. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;addBehavior(url)&lt;/b&gt; Attaches the DHTML Behavior referenced by string url to the element. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;addEventListener(whichEvent, handler, direction)&lt;/b&gt; Instructs the object to execute the function handler whenever an event of type given in the string whichEvent (for example, "click") occurs. The direction is a Boolean specifying the phase in which to fire, true for capture or false for bubbling. (MOZ/N6+, DOM2)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;appendChild(newChild)&lt;/b&gt; Appends newChild to end of the node’s childNodes[] list. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;applyElement(newElement [, where])&lt;/b&gt; "Applies" one element to another by enclosing one within the other. If where is omitted or has value "outside", the object referenced by newElement becomes the parent of the current element. Otherwise, newElement becomes the only child of the current element, enclosing all of the current element’s children. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;attachEvent(whichHandler, theFunction)&lt;/b&gt; Attaches the function theFunction as a handler specified by the string whichHandler, for example, "onclick". (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;blur()&lt;/b&gt; Removes focus from the element. (IE5+ for most elements. For form fields N2+ or N3+ and IE3+ or IE4+ and DOM1, listed specifically for each object)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;clearAttributes()&lt;/b&gt; Clears all nonessential HTML attributes from the element (leaves id, dir, etc.). (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;click()&lt;/b&gt; Simulates a mouse click at the object. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;cloneNode(cloneChildren)&lt;/b&gt; Clones the node and returns the new clone. If cloneChildren is true, the returned node includes the recursively constructed subtree of clones of the node’s children. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;componentFromPoint(x, y)&lt;/b&gt; Returns a string that gives information about the pixel coordinate (x,y) in the client window with respect to the current element. The string returned may have one of the values in the following table [tabela 2]. The return value specifies whether the coordinate is inside of the element (""), outside of the element ("outside"), or a part of the various scrolling mechanisms that may be displayed for the element.&lt;br /&gt;&lt;br /&gt;This method is often used with events to determine where user activity is taking place with respect to a particular element and to take special actions based on scroll bar manipulation. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;contains(element)&lt;/b&gt; Returns a Boolean indicating if the object given in element is contained within the element. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;detachEvent(whichHandler, theFunction)&lt;/b&gt; Instructs the object to cease executing the function theFunction as a handler given the string whichHandler, for example, "onclick". (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;dispatchEvent(event)&lt;/b&gt; Causes the Event instance event to be processed by the object’s appropriate handler. Used to redirect events. (MOZ/N6+, DOM2)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;dragDrop()&lt;/b&gt; Initiates a drag event at the element. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;fireEvent(handler [, event])&lt;/b&gt; Causes the event handler given by the string handler to fire. If an Event instance was passed as event, the new event created reflects the properties of event. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;focus()&lt;/b&gt; Gives focus to the element.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getAdjacentText(where)&lt;/b&gt; Returns the string of text corresponding to the text string at position where, with respect to the current node. The where parameter is a string with the following values [tabela 3]&lt;br /&gt;&lt;br /&gt;There is no standard DOM method that mimics this behavior. Instead, you must examine the previousSibling, firstChild, lastChild, or nextSibling (in order corresponding to the values of where in the preceding table) and extract the string manually from their text node(s). (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getAttribute(name)&lt;/b&gt; Returns a string containing the value of the attribute specified in the string name or null if it does not exist. (IE4+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getAttributeNode(name)&lt;/b&gt; Returns the attribute node corresponding to the attribute in the string name. (IE6+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getBoundingClientRect()&lt;/b&gt; Retrieves a TextRectangle with properties top, bottom, left, right indicating the pixel values of the rectangle in which the element’s content is enclosed. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getClientRects()&lt;/b&gt; Retrieves a collection of TextRectangle objects, which give the pixel coordinates of all bounding rectangles contained in the element. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getElementsByTagName(tagname)&lt;/b&gt; Retrieves a collection of elements corresponding to the tag given in string tagname. A value of "*" retrieves all tags. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getExpression(propertyName)&lt;/b&gt; Retrieves the string giving the dynamic property expression for the property/attribute named propertyName. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;hasAttribute(name)&lt;/b&gt; Returns a Boolean indicating if the attribute given in string name is defined for the node (explicitly or by default). (MOZ/N6+, DOM2 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;hasAttributes()&lt;/b&gt; Returns a Boolean indicating if any attributes are defined for the node. (MOZ/N6+, DOM2 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;hasChildNodes()&lt;/b&gt; Returns a Boolean indicating if the node has children. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;insertAdjacentElement(where, element)&lt;/b&gt; Inserts the element object given in element adjacent to the current element in the position given by the string where (IE5+).The possible values for where include these [tabela 4]&lt;br /&gt;&lt;br /&gt;&lt;b&gt;insertAdjacentHTML(where, text)&lt;/b&gt; Inserts the HTML given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is parsed and added to the document tree. (IE5+) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;insertAdjacentText(where, text)&lt;/b&gt; Inserts the text given in string text adjacent to the current element according to the string where. See table under insertAdjacentElement() for the meaning of this parameter. The text is not parsed as HTML. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;insertBefore(newChild, refChild)&lt;/b&gt; Inserts node newChild in front of refChild in the childNodes[] list of refChild's parent node. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isSupported(feature [, version])&lt;/b&gt; Returns a Boolean indicating whether feature and version given in the argument strings are supported. (MOZ/N6+, DOM2 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;mergeAttributes(source [, preserve])&lt;/b&gt; Merges all attributes, styles, and event handlers from the element node source into the current element. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;normalize()&lt;/b&gt; Recursively merges adjacent text nodes in the sub-tree rooted at this element. (IE6+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;releaseCapture()&lt;/b&gt; Disables universal mouse event capturing at that object. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeAttribute(name)&lt;/b&gt; Removes attribute corresponding to string name from the node. (IE4+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeAttributeNode(attribute)&lt;/b&gt; Removes the attribute node given by node attribute and returns the removed node. (IE6+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeBehavior(id)&lt;/b&gt; Removes the DHTML Behavior associated with id (previously returned by attachBehavior()) from the element. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeChild(oldChild)&lt;/b&gt; Removes oldChild from the node’s children and returns a reference to the removed node. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeEventListener(whichEvent, handler, direction)&lt;/b&gt; Removes function handler as a handler for the event given in the string whichEvent (for example, "click") for the phase given by the Boolean direction. (MOZ/N6+, DOM2)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;removeExpression(propertyName)&lt;/b&gt; Removes dynamic property expression for the property given in the string propertyName. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;replaceAdjacentText(where, text)&lt;/b&gt; Replaces the text at position where relative to the current node with the text (non-HTML) string text (IE5+). Possible values for where include [tabela 5]&lt;br /&gt;&lt;br /&gt;&lt;b&gt;replaceChild(newChild, oldChild)&lt;/b&gt; Replaces the node’s child node oldChild with node newChild. (IE5+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;replaceNode(newNode)&lt;/b&gt; Replaces the current node with newNode. (IE5+) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;scrollIntoView([alignToTop])&lt;/b&gt; Causes the object to be immediately scrolled into the viewable area of the window. If alignToTop is true or omitted, the top of the object is aligned with the top of the window (if possible). Otherwise, if alignToTop is false, the object is scrolled so that the bottom of the object is aligned with the bottom of the viewable window. (IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setActive()&lt;/b&gt; Sets the object as the active object without giving it focus. (IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setAttribute(name, value)&lt;/b&gt; Sets a new attribute for the node with name and value given by the string arguments. (IE4+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setAttributeNode(newAttr)&lt;/b&gt; Adds the attribute node newAttr (replacing and returning any attribute node with the same name). (IE6+, MOZ/N6+, DOM1 Core)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setCapture([containerCapture])&lt;/b&gt; Causes all mouse events occurring in the document to be sent to this object. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setExpression(property, expression [, language])&lt;/b&gt; Sets the expression given in string expression as the dynamic expression for the property given in string property. The optional language parameter specifies which scripting language the expression is written in, for example, "VBscript" (JScript is the default). Commonly used as a method of element nodes and Style objects. Used for setting dynamic expressions. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;swapNode(node)&lt;/b&gt; Exchanges the location of the object with node in the object hierarchy. (IE5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;unwatch(property)&lt;/b&gt; Removes the watchpoint on the property given in the string property. (N4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;watch(property, handler)&lt;/b&gt; "Watches" the property given in string property and invokes the function handler whenever its value changes. The handler is passed the name of the property, the old value, and the value to which it is being set. Any value the function returns is interpreted as the new value for the property. (N4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Notes&lt;/b&gt;&lt;br /&gt;With the exception of the object scriptable under traditional models (Form, Image, and so on), most elements become scriptable in Internet Explorer 4+, Mozilla/Netscape 6+, and DOM1.&lt;br /&gt;&lt;br /&gt;HTML elements are referred to both in uppercase and lowercase under the DOM, so &amp;lt;p&amp;gt; and &amp;lt;P&amp;gt; are both equivalent to an HTMLParagraph object.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Tabela 1&lt;/b&gt;&lt;br /&gt;&lt;table border="1" cellspacing="1" cellpadding="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;th&gt;Node Type Number&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Type&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Description&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Example&lt;/th&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;1&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Element&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;An HTML or XML element&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;&amp;lt;p&amp;gt;…&amp;lt;/p&amp;gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;2&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Attribute&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;An attribute for an HTML or XML element&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;align="center"&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;3&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Text&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;A fragment of text that would be enclosed by an HTML or XML element&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;This is a text fragment!&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;8&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Comment&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;An HTML comment&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;&amp;lt;!-- This is a comment --&amp;gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;9&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Document&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;The root document object, namely the top element in the parse tree&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;&amp;lt;html&amp;gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;10&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;DocumentType&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;A document type definition&lt;/td&gt;&lt;br /&gt;  &lt;td&gt; &amp;lt;!DOCTYPE HTML PUBLIC "-//W3C&lt;br /&gt;&lt;br /&gt;//DTD HTML 4.01 Transitional//EN"&lt;br /&gt;&lt;br /&gt;"http://www.w3.org/TR/html4/loose.dtd"&amp;gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Tabela 2&lt;/b&gt;&lt;br /&gt;&lt;table border="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;th&gt;Return Value&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Component at the Given Coordinate&lt;/th&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;""&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Component is inside the client area of the object.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"outside"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Component is outside the bounds of the object.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarDown"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Down scroll arrow is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarHThumb"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt; Horizontal scroll thumb or box is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarLeft"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Left scroll arrow is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarPageDown"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Page-down scroll bar shaft is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarPageLeft"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Page-left scroll bar shaft is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarPageRight"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Page-right scroll bar shaft is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarPageUp"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Page-up scroll bar shaft is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarRight"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Right scroll arrow is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarUp"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt; Up scroll arrow is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"scrollbarVThumb"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Vertical scroll thumb or box is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleBottom"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Bottom sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleBottomLeft"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Lower-left sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleBottomRight"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Lower-right sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleLeft"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Left sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleRight"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Right sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleTop"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Top sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleTopLeft"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Upper-left sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"handleTopRight"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Upper-right sizing handle is at the specified location.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Tabela 3&lt;/b&gt;&lt;br /&gt;&lt;table border="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;th&gt;Value of where&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;String Returned&lt;/th&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Text immediately preceding element’s opening tag (back to but not including first element encountered).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Text immediately following the element’s opening tag (up to but not including the first nested element).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Text immediately preceding the element’s closing tag (back to but not including the closing tag of the last enclosed element).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Text immediately following element’s closing tag (up to but not including the first following tag).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Tabela 4&lt;/b&gt;&lt;br /&gt;&lt;table border="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;th&gt;Value of where&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Effect&lt;/th&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Inserts immediately before the object.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Inserts after the start of the object but before all other content.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Inserts immediately before the end of the object, after all other content.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Inserts immediately after the end of the object.&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Tabela 5&lt;/b&gt;&lt;br /&gt;&lt;table border="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;th&gt;Value of where&lt;/th&gt;&lt;br /&gt;  &lt;th&gt;Effect&lt;/th&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Replaces text immediately before the object (back to but not including first tag or end tag encountered).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterBegin"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Replaces text at the start of the object but before all other enclosed content (up to but not including first opening tag).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"beforeEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Replaces text immediately before the end of the object, after all other content (back to but not including last tag or closing tag).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;"afterEnd"&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;Replaces text immediately after the element’s closing tag (up to but not including the next tag).&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-116162497602437999?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/116162497602437999/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=116162497602437999&amp;isPopup=true' title='6 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/116162497602437999'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/116162497602437999'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/10/dom-bsico.html' title='DOM - Básico'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115954179261976704</id><published>2006-09-29T11:51:00.000-03:00</published><updated>2006-10-19T01:29:06.343-03:00</updated><title type='text'>Outros objetos Built-In</title><content type='html'>Olá meus queridos leitores.&lt;br /&gt;Hoje vamos continuar nossos estudos pelos objetos Built-In e finaliza-los!&lt;br /&gt;&lt;br /&gt;Lembrando, eu não cobri todos os objetos Built-In, eu cobri os principais e mais usados. Hoje vamos ver os próximos, let's go!&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Objeto Date&lt;/b&gt;&lt;br /&gt;Como o nome diz, o objeto Date serve para trabalhar com datas em JavaScript, vamos ao primeiro exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var d = new Date();&lt;br /&gt;alert(d.toString());&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Iniciando o objeto Date sem usar parâmetros nós pegamos a data atual do computador do cliente, usando o &lt;b&gt;toString()&lt;/b&gt; conseguimos a data no formato GMT.&lt;br /&gt;Vamos agora a um caso mais expecífico:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var d = new Date();&lt;br /&gt; &lt;br /&gt;alert(d.getFullYear()); //ano&lt;br /&gt;alert(d.getMonth()); //mes&lt;br /&gt;alert(d.getDate()); //dia&lt;br /&gt;alert(d.getHours()); //hora&lt;br /&gt;alert(d.getMinutes()); //minutos&lt;br /&gt;alert(d.getSeconds()); //segundos&lt;br /&gt;alert(d.getMilliseconds()); //mili segundos&lt;br /&gt;alert(d.getDay()); //dia da semana&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como visto acima, podemos pegar separadamente cada parte do tempo. O objeto Date é apenas isso mesmo, um problema muito normal é quando a pessoa quer fazer um calendário, o problema é que o JavaScript não da suporte nativo para dizer quantos dias tem o mês atual, mas isso não é nada que não possamos implementar:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Date.prototype.getMonthDays = function() {&lt;br /&gt; var days = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];&lt;br /&gt; &lt;br /&gt; var bisexto = false;&lt;br /&gt; var ano = this.getFullYear();&lt;br /&gt; &lt;br /&gt; if ((((ano % 4) == 0) &amp;&amp; ((ano % 100) != 0)) || ((ano % 400) == 0)) {&lt;br /&gt;  bisexto = true;&lt;br /&gt; }&lt;br /&gt; &lt;br /&gt; days[1] = bisexto ? 29 : 28;&lt;br /&gt; &lt;br /&gt; var mes = this.getMonth();&lt;br /&gt; &lt;br /&gt; return days[mes];&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var d;&lt;br /&gt;d = new Date();&lt;br /&gt;alert(d.getMonthDays());&lt;br /&gt;d = new Date(2006, 1, 12);&lt;br /&gt;alert(d.getMonthDays());&lt;br /&gt;d = new Date(2006, 0, 3);&lt;br /&gt;alert(d.getMonthDays());&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Percebam que podemos criar um objeto date informando a data para o objeto, isso é muito útil em caléndarios principalmente. Uma observação importante é que os mesês começam em 0 e não em 1, então 0 é janeiro, 1 é fevereiro...&lt;br /&gt;Prontinho, agora ao usarmos o método &lt;b&gt;getMonthDays&lt;/b&gt; teremos como retorno a quantidade de dias do mês, até que nem foi dificil.&lt;br /&gt;&lt;br /&gt;Para terminar, vamos criar um relógio digital usando JavaScript, iremos usar um pouco de DOM dessa vez que já é pra dar um gostinho do próximo artigo (que será sobre DOM):&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&amp;lt;html&amp;gt;&lt;br /&gt; &amp;lt;head&amp;gt;&lt;br /&gt;  &amp;lt;title&amp;gt;Rel&amp;oacute;gio Virtual - JavaScript Developer&amp;lt;/title&amp;gt;&lt;br /&gt;  &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;   var updateTime = function() {&lt;br /&gt;   var obj = document.getElementById('relogio');&lt;br /&gt;   var date = new Date();&lt;br /&gt;   var dateString = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();&lt;br /&gt;   &lt;br /&gt;   obj.innerHTML = dateString;&lt;br /&gt;   setTimeout(updateTime, 1000);&lt;br /&gt;   };&lt;br /&gt;   &lt;br /&gt;   window.onload = updateTime;&lt;br /&gt;  &amp;lt;/script&amp;gt;&lt;br /&gt; &amp;lt;/head&amp;gt;&lt;br /&gt; &amp;lt;body&amp;gt;&lt;br /&gt;  &amp;lt;div id=&amp;quot;relogio&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;br /&gt; &amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Sem miraculosidades, a função &lt;b&gt;updateTime&lt;/b&gt; pega uma referência para o DIV com id relógio (usando o document.getElementById(), vamos ver isso melhor na próxima aula), depois pega a data atual, cria uma string com a hora atual, troca o conteúdo da DIV (usando a propriedade innerHTML) e finalmente manda que ela seja executada novamente após 1 segundo (usando setTimeout()).&lt;br /&gt;Isso é tudo que eu tenho a dizer sobre o objeto Date, vamos ao próximo.&lt;br /&gt;&lt;br /&gt;Referência do objeto Date:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;Date (Built-in Object)&lt;/b&gt;&lt;br /&gt;The Date object provides a wide variety of methods for manipulating dates and times. It is important to remember that Date instances do not contain a “ticking clock” but rather hold a static date value. Internally, the date is stored as the number of milliseconds since the epoch (midnight of January 1, 1970 UTC). This accounts for the prominent role of milliseconds in many Date methods.&lt;br /&gt;&lt;br /&gt;Milliseconds, seconds, minutes, hours, and months are enumerated beginning with zero; so, for example, December is month 11. Days are enumerated beginning with 1. Years should always be given using four digits. Modern implementations permit years as much as several hundred thousand years in the past or future, although older implementations often have trouble handling dates before 1970. Many implementations have trouble handling dates before 1 A.D.&lt;br /&gt;&lt;br /&gt;Note that Universal Coordinated Time (UTC) is the same as Greenwich Mean Time (GMT).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new Date(); &lt;br /&gt;&lt;br /&gt;var instanceName = new Date(milliseconds); &lt;br /&gt;&lt;br /&gt;var instanceName = new Date(stringDate); &lt;br /&gt;&lt;br /&gt;var instanceName = new Date(year, month, day [, hrs [, mins [, secs [, ms]]]]); &lt;br /&gt;&lt;br /&gt;The first constructor syntax creates a new Date instance holding the current date and time. The second syntax creates an instance holding the date given by the number of milliseconds given in the numeric milliseconds argument. The third syntax attempts to create an instance by converting the string stringDate into a valid date using the parse() method (see under the “Methods” section). The fourth syntax creates an instance according to its numeric arguments. If the optional parameters are omitted, they are filled with zero.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;constructor&lt;/b&gt; Reference to the constructor object, which created the object. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;getDate()&lt;/b&gt; Returns a numeric value indicating the day of the month (1-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getDay()&lt;/b&gt; Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getFullYear()&lt;/b&gt; Returns a numeric value indicating the four-digit year. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getHours()&lt;/b&gt; Returns a numeric value indicating the hours since midnight (0-based). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getMilliseconds()&lt;/b&gt; Returns a numeric value indicating the number of milliseconds (0-999). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getMinutes()&lt;/b&gt; Returns a numeric value indicating the number of minutes (0–59). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getMonth()&lt;/b&gt; Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getSeconds()&lt;/b&gt; Returns a numeric value indicating the number of seconds (0–59). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getTime()&lt;/b&gt; Returns a numeric value indicating the number of milliseconds since the epoch. Dates before the epoch return a negative value indicating the number of milliseconds before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getTimezoneOffset()&lt;/b&gt; Returns a numeric value indicating the difference in minutes between the local time and the UTC. Positive values indicate the local time is behind UTC (for example, in the United States) and negative values indicate the local time is ahead of UTC (for example, in India). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCDate()&lt;/b&gt; Returns a numeric value indicating the day of the month (1-based) using UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCDay()&lt;/b&gt; Returns a numeric value indicating the day of the week (0 for Sunday, 1 for Monday, and so on) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCFullYear()&lt;/b&gt; Returns a numeric value indicating the four-digit year according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCHours()&lt;/b&gt; Returns a numeric value indicating the hours since midnight (0-based) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCMilliseconds(&lt;/b&gt;) Returns a numeric value indicating the number of milliseconds (0–999) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCMinutes()&lt;/b&gt; Returns a numeric value indicating the number of minutes (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCMonth()&lt;/b&gt; Returns a numeric value indicating the number of months since the beginning of the year (0–11; 0 is January) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getUTCSeconds()&lt;/b&gt; Returns a numeric value indicating the number of seconds (0–59) according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getYear()&lt;/b&gt; Returns the current year minus 1900 or in some cases a four-digit year if the year is greater than 1999. This method is deprecated; use getFullYear() instead. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;getVarYear()&lt;/b&gt; Returns the VT_DATE corresponding to the object. For use with interaction with COM or VBScript, but in general should be avoided. (IE4+ (JScript 3.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parse(stringDate)&lt;/b&gt; Attempts to parse the date given in the string stringDate and if successful returns the number of milliseconds of the date relative to the epoch. Valid strings are given in Chapter 7 but in general can be any common representation of a date, for example "month/day/year", "month day, year", or "month day, year hh:mm:ss". Unambiguous shorthand (for example, "Dec" for December) is permitted. If the date cannot be parsed, NaN is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1, Static)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setDate(dayOfMonth)&lt;/b&gt; Sets the day of the month (1-based) in local time as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setFullYear(year [, month [, day]])&lt;/b&gt; Sets the date to the year given in the numeric argument year in local time. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setHours(hours [, mins [, secs [, ms]]])&lt;/b&gt; Sets the hours (0-based) to the numeric argument given in hours in local time. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setMilliseconds(ms)&lt;/b&gt; Sets the milliseconds (0-based) to the numeric argument ms in local time. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setMinutes(minutes [, secs [, ms]])&lt;/b&gt; Sets the minutes (0-based) to the numeric argument minutes in local time. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;setMonth(month [, day])&lt;/b&gt; Sets the month (0-based) to the numeric argument month in local time. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12 the year is incremented and the month is set to zero). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setSeconds(seconds [, ms])&lt;/b&gt; Sets the seconds (0-based) to the numeric argument seconds in local time. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setTime(ms)&lt;/b&gt; Sets the date to the date given by the number of milliseconds since the epoch given in ms. Negative values of ms specify dates before the epoch. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCDate(dayOfMonth)&lt;/b&gt; Sets the day of the month (1-based) in UTC as given by the numeric parameter dayOfMonth. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCFullYear(year [, month [, day]])&lt;/b&gt; Sets the date to the year given in the numeric argument year in UTC. If the numeric parameters month and day are passed, the month (0-based) and day of the month (1-based) are set as well. If month is greater than 11, the year is incremented accordingly. If day is greater than the number of days in the month, the month is incremented accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCHours(hours [, mins [, secs [, ms]]])&lt;/b&gt; Sets the hours (0-based) to the numeric argument given in hours in UTC. If the optional parameters are passed, the minutes, seconds, and milliseconds are set accordingly. If any of the parameters is greater than the normal range of values, the date is adjusted accordingly (for example, a value of 60 seconds increments the minutes by one and sets the seconds to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCMilliseconds(ms)&lt;/b&gt; Sets the milliseconds (0-based) to the numeric argument ms in UTC. If ms is greater than 999, the seconds are adjusted accordingly. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCMinutes(minutes [, secs [, ms]])&lt;/b&gt; Sets the minutes (0-based) to the numeric argument minutes in UTC. If numeric arguments secs and ms are supplied, the seconds and milliseconds are set to these values. If any argument is greater than the normal range, appropriate values are incremented accordingly (for example, if secs is 60, the minute is incremented by one and the seconds set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCMonth(month [, day])&lt;/b&gt; Sets the month (0 based) to the numeric argument month in UTC. If the numeric argument day is supplied, the day of the month (1-based) is set accordingly. If either value is outside of the expected range, the date is adjusted accordingly (for example, if month is 12, the year is incremented and the month is set to zero). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;setUTCSeconds(seconds [, ms])&lt;/b&gt; Sets the seconds (0-based) to the numeric argument seconds in UTC. If numeric argument ms is supplied, the milliseconds (0-based) are set accordingly. If either value is outside the expected range, the date is adjusted accordingly (for example, if ms is 1000, then the seconds are incremented and milliseconds set to 0). (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;setYear(year)&lt;/b&gt; This method is deprecated; use setFullYear() instead. Sets the year to the numeric value year in local time. The year parameter must be the desired year minus 1900. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toGMTString()&lt;/b&gt; This method is deprecated; use toUTCString() instead. Returns the string representation of the date relative to GMT. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toLocaleString()&lt;/b&gt; Returns the date converted to a string formatted according to local conventions as defined by the operating system. For example, the U.S. uses month/day/year whereas Europe uses day/month/year. The return value is not to be used for computation, but rather for display to the user. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns the date as a string. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toUTCString()&lt;/b&gt; Returns the date formatted as a string according to UTC. (IE4+ (JScript 3.0+), MOZ, N4.06+ (JavaScript 1.3+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;UTC(year, month, day [, hours [, mins [, secs [, ms]]]])&lt;/b&gt; This static method returns a numeric value indicating the number of milliseconds between the epoch and the date given by the numeric parameters. Any parameters outside of their expected range cause the date to be adjusted accordingly. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;valueOf()&lt;/b&gt; Returns a numeric value indicating the number of milliseconds difference between the date and the epoch. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE3+ (JScript 1.0+), Mozilla, N2+ (JavaScript 1.0+), ECMAScript Edition 1.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Notes&lt;/b&gt;&lt;br /&gt;The Date object is seriously broken in older browsers. The authors suggest avoiding its use except in the most basic tasks in browsers earlier than IE4 and Netscape 4.&lt;br /&gt;&lt;br /&gt;The Date object cannot be enumerated directly using for/in.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Objeto Global&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Esse é o objeto mais desconhecido e conhecido ao mesmo tempo, muitos usam ele e nem sabem da sua existência.&lt;br /&gt;O objeto Global é um objeto estático (não pode ser instanciado, você não pode fazer: a = new Global()), e assim só tem métodos estáticos. O objeto global pode ser acesso de qualquer lugar, é até meio complicado falar dele, pois ele não tem nada específico, então eu prefiro falar diretamente de suas constates e métodos:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;método eval&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Esse talvez sejá o método mais conhecido do objeto Global, muitos que ja mexeram com JavaScript devem te-lo usado.&lt;br /&gt;Para quem não conhece, o eval consegue pegar um string, e executa-la como se fosse código, exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "alert('codigo a ser executado por eval')";&lt;br /&gt;eval(a);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;A variável &lt;b&gt;a&lt;/b&gt; contém dentro dela uma string, e o eval executa essa string como se fosse código, veremos bem sua utilidade ao estudar-mos Ajax, pois o melhor padrão atual para transferencia de dados (o JSON), usa diretamente o eval para ler o conteudo.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;método parseInt&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;O método parseInt converte uma string em número, exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = '5';&lt;br /&gt;var b = '6';&lt;br /&gt;&lt;br /&gt;alert(a + b);&lt;br /&gt;alert(parseInt(a) + parseInt(b));&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;constantes&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Infinity - contem um valor de infinito (um número quando ultrapassa o limite do javascript)&lt;br /&gt;NaN - Not a Number, constante para calculos erroneos que não retornaram um número&lt;br /&gt;undefined - para variáveis indefinidas&lt;br /&gt;&lt;br /&gt;Isso é o principal do Global, o resto eu deixo pela referência:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;Global (Built-in Object)&lt;/b&gt;&lt;br /&gt;The Global object provides methods and constants that can be used freely anywhere in your scripts. Global is defined to be the globally enclosing context, so this object cannot be instantiated or even directly accessed; its properties and methods are always within the scope of an executing script. Its sole purpose is as a catch-all for globally available methods and constants.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;This object cannot be instantiated because it defines the global context and thus has no constructor.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;Infinity&lt;/b&gt; Constant holding the numeric value Infinity. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;NaN&lt;/b&gt; Constant holding the numeric value NaN (not a number). (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;undefined&lt;/b&gt; Constant holding the value undefined. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;decodeURI(encodedURI)&lt;/b&gt; URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;decodeURIComponent(encodedURI)&lt;/b&gt; URI-decodes the string encodedURI and returns the decoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;encodeURI(uri)&lt;/b&gt; URI-encodes the string uri, treating uri as a full URI. Legal URI characters (for example, the :// after the protocol) are not encoded. Returns the encoded string. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;encodeURIComponent(uriComponent)&lt;/b&gt; URI-encodes the string uriComponent and returns the encoded string. All potentially problematic characters (for example, / and ?) are encoded. (IE5.5+ (JScript 5.5+), MOZ/N6+ (JavaScript 1.5+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;escape(string)&lt;/b&gt; URI-encodes string and returns the encoded string. Using the newer encodeURIComponent() is preferable. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;eval(string&lt;/b&gt;) Executes string as JavaScript. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isFinite(value)&lt;/b&gt; Returns a Boolean indicating if the numeric argument value is finite. Returns false if value is NaN. (IE4+ (JScript 3.0+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isNaN(value)&lt;/b&gt; Returns a Boolean indicating if the numeric argument value is NaN. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parseFloat(string)&lt;/b&gt; Parses string as a floating-point number and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;parseInt(string)&lt;/b&gt; Parses string as an integer and returns its value. If string cannot be converted, NaN is returned. (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;unescape(encodedString)&lt;/b&gt; URI-decodes encodedString and returns the decoded string. Using the newer decodeURIComponent() method is preferable. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), Mozilla, ECMAScript Edition 1.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Por hoje é apenas isso, no próximo começaremos o DOM, ai vai ficar mais legal, vamos ver como mexer com elementos html e alguns efeitos simples ;). Até lá.&lt;br /&gt;&lt;br /&gt;Só para complementar, quando eu postei sobre objetos eu esqueci de deixar a referência do &lt;b&gt;Object&lt;/b&gt;, vou coloca-la abaixo e também vou adiciona-la no post de objetos:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal"&gt;&lt;b&gt;Object (Built-in Object)&lt;/b&gt;&lt;br /&gt;Object is the basic object from which all other objects are derived. It defines methods common to all objects that are often overridden to provide functionality specific to each object type. For example, the Array object provides a toString() method that functions as one would expect an array’s toString() method to behave.This object also permits the creation of user-defined objects and instances are quite often used as associative arrays.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new Object(); &lt;br /&gt;&lt;br /&gt;This statement creates a new (generic) object.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; The prototype for the object. This object defines the properties and methods common to all objects of this type. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;hasOwnProperty(property)&lt;/b&gt; Returns a Boolean indicating whether the object has an instance property by the name given in the string property. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isPrototypeOf(obj)&lt;/b&gt; Returns a Boolean indicating if the object referenced by obj is in the object’s prototype chain. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;propertyIsEnumerable(property)&lt;/b&gt; Returns a Boolean indicating if the property with the name given in the string property will be enumerated in a for/in loop. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toSource()&lt;/b&gt; Returns a string containing a JavaScript literal that describes the object. (MOZ, N4.06+ (JavaScript 1.3+)) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns the object a string, by default "[object Object]". Very often overridden to provide specific functionality. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;unwatch(property)&lt;/b&gt; Disables watching of the object’s property given by the string property. (N4 (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;valueOf()&lt;/b&gt; Returns the primitive value associated with the object, by default the string "[object Object]". Often overridden to provide specific functionality. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;watch(property, handler)&lt;/b&gt; Sets a watch on the object’s property given in string property. Whenever the value of the property changes, the function handler is invoked with three arguments: the name of the property, the old value, and the new value it is being set to. The handler can override the setting of the new value by returning a value, which is set in its place. (N4 (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Todos os objetos do JavaScript contém os métodos e propriedades acima, com raras excessões. Falow!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115954179261976704?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115954179261976704/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115954179261976704&amp;isPopup=true' title='4 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115954179261976704'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115954179261976704'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/outros-objetos-built-in.html' title='Outros objetos Built-In'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115887788767778688</id><published>2006-09-21T19:31:00.000-03:00</published><updated>2006-09-28T08:53:22.273-03:00</updated><title type='text'>Strings e Expressões Regulares</title><content type='html'>Boa noite galera, agreço as visitas e os comentários, continuem sempre assim ;).&lt;br /&gt;&lt;br /&gt;Como mensionado antes, hoje vou falar sobre &lt;b&gt;Strings&lt;/b&gt; e &lt;b&gt;Expressões Regulares&lt;/b&gt;, bom, eu não pretendo me fixar no assunto de expressões regulares, eu apenas mostrarei como usa-las no JavaScript, pra quem quizer estudar expressões regulares, acesse esse site: &lt;a href="http://guia-er.sourceforge.net/"&gt;http://guia-er.sourceforge.net/&lt;/a&gt; esse é melhor site sobre expressões regulares que eu conheco, quem quizer estude por ele, pois é muito bom.&lt;br /&gt;&lt;br /&gt;Voltando ao nosso assunto, hoje aprenderemos a manusear &lt;b&gt;Strings&lt;/b&gt; usando JavaScript, vamos ver inicialmente a criação de strings:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "primeira string";&lt;br /&gt;var b = new String("de outro modo");&lt;br /&gt;&lt;br /&gt;alert(a);&lt;br /&gt;alert(b);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Isso é bem simples, como vocês devem saber, strings devem ficar dentro aspas, no JavaScript você pode tanto usar aspas simples como duplas, isso não vai interferir em nada.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Comparação de Strings&lt;/b&gt;&lt;br /&gt;Temos que ter uma atenção nessa parte, a comparação de strings pode ser feita usando o operador &lt;b&gt;==&lt;/b&gt;, mas fazer a comparação dessa forma deixa um risco, porque o operador &lt;b&gt;==&lt;/b&gt; vai comparar a referência dos objetos, vamos ver em exemplos isso:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "teste";&lt;br /&gt;var b = "teste";&lt;br /&gt;&lt;br /&gt;if(a == b)&lt;br /&gt; alert('a e b sao iguais');&lt;br /&gt;else&lt;br /&gt; alert('a e b sao diferentes');&lt;br /&gt;&lt;br /&gt;var c = new String("teste");&lt;br /&gt;var d = new String("teste");&lt;br /&gt;&lt;br /&gt;if(c == d)&lt;br /&gt; alert('c e d sao iguais');&lt;br /&gt;else&lt;br /&gt; alert('c e d sao diferentes');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como podem ver, oque acontece é que quanto definimos &lt;b&gt;a&lt;/b&gt; e &lt;b&gt;b&lt;/b&gt; daquela forma, ele acaba usando strings &lt;b&gt;cacheadas&lt;/b&gt; (guardas no mesmo ponto de memória para melhorar o desempenho), ja usando &lt;b&gt;new String&lt;/b&gt; com &lt;b&gt;c&lt;/b&gt; e &lt;b&gt;d&lt;/b&gt; ele força uma nova alocação, assim as refencias ficam diferetes, e acaba que na comparação ele considara as strings diferentes (mesmo o texto sendo exatamente igual). Para resolver isso, fazemos uma coisa meio bizarra, prefiro explicar com codigos:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "teste";&lt;br /&gt;var b = "teste";&lt;br /&gt;&lt;br /&gt;if(a == b)&lt;br /&gt; alert('a e b sao iguais');&lt;br /&gt;else&lt;br /&gt; alert('a e b sao diferentes');&lt;br /&gt;&lt;br /&gt;var c = new String("teste");&lt;br /&gt;var d = new String("teste");&lt;br /&gt;&lt;br /&gt;if(c.toString() == d.toString())&lt;br /&gt; alert('c e d sao iguais');&lt;br /&gt;else&lt;br /&gt; alert('c e d sao diferentes');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Pronto, agora nossa comparação de &lt;b&gt;c&lt;/b&gt; com &lt;b&gt;d&lt;/b&gt; retornou verdadeira.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Operador de concatenação e caracteres de escape&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;Para concatenar strings não tem segredo, basta usar o operador de soma:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 'oi';&lt;br /&gt;var b = 'visitante';&lt;br /&gt;&lt;br /&gt;alert(a + ' ' + b);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Mas um porém é quando queremos concatenar números, como se fossem strings, para isso temos que concatenar o número a uma string, vamos ver como concatenas dois números:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 5;&lt;br /&gt;var b = 9;&lt;br /&gt;&lt;br /&gt;alert(a + '' + b);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Usando uma string, mesmo que seja vazia, ao somar com um número ele transforma aquele número em uma string, assim temos a concatenção e não a soma dos números.&lt;br /&gt;&lt;br /&gt;Caracteres de escape são caracteres que existem mas não são vistos exatamente, como por exemplo o enter, para as pessoas o enter é um separador de linha, para o computador é apenas mais um caractere, para escrever uma linha do windows (que usa 2 caracateres) escreveriamos "\r\n" que para o JavaScript o \r eh transformado em um caractere, e o \n em outro, isso forma uma linha no windows, em muitos casos podemos usar apenas o \n, pois ele ja resolver, vamos ver a tabela dos caracteres escapados no JavaScript:&lt;br /&gt;&lt;br /&gt;&lt;table border="1"&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;&lt;b&gt;Caractere&lt;/b&gt;&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;&lt;b&gt;Resultado&lt;/b&gt;&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;\n&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;nova linha&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;\r&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;retorno de carro&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;\t&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;tabulação&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt; &lt;tr&gt;&lt;br /&gt;  &lt;td&gt;\\&lt;/td&gt;&lt;br /&gt;  &lt;td&gt;insere uma barra&lt;/td&gt;&lt;br /&gt; &lt;/tr&gt;&lt;br /&gt;&lt;/table&gt;&lt;br /&gt;&lt;br /&gt;Existem mais, mas esses são os mais usados. Como as strings sao representadas dentro de aspas, as vezes precisamos usar essas aspas dentro da string, para isso usamos o escape \" ou \' dependendo do seu caso, vamos ver um exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;alert("texto em \"aspas\"");&lt;br /&gt;alert('texto em \'aspas\'');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Métodos de String&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;As Strings do JavaScript não tem tantos métodos quanto precisamos hoje em dia, ela tem os mais básicos, por isso muitas pessoas fazem uma implementação de extensão para as strings (usando seu prototype e adicionando mais recursos), em artigos futuros faremos uma implementação desse gênero, adicionando vários recursos. Mas o JavaScript tem seus recursos, então vamos conhece-los:&lt;br /&gt;&lt;br /&gt;Quando precisamos pegar um caractere expecífico em uma string, usamos o método &lt;b&gt;charAt&lt;/b&gt;:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "abcde";&lt;br /&gt;&lt;br /&gt;alert(a.charAt(1));&lt;br /&gt;alert(a.charAt(4));&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Lembre-se sempre que a indexção começa em zero, entao o primeiro caractere é o zero, o segundo é um e por ai vai.&lt;br /&gt;&lt;br /&gt;Muito parecido com o &lt;b&gt;charAt&lt;/b&gt; temos o &lt;b&gt;charCodeAt&lt;/b&gt; que funciona da mesma maneira, mas no lugar de retornar o caractere, ele retorna um número inteiro, que no caso é o codigo ASCII do caractere (quem quizer, acesse &lt;a href="http://www.asciitable.com/"&gt;http://www.asciitable.com/&lt;/a&gt; para ver a tabela completa).&lt;br /&gt;&lt;br /&gt;Um método que vai um pouco além do &lt;b&gt;charAt&lt;/b&gt; é o método &lt;b&gt;substring&lt;/b&gt;, esse método pega um bloco da string:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "abcde";&lt;br /&gt;&lt;br /&gt;alert(a.substring(0, 2));&lt;br /&gt;alert(a.substring(1, 4));&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;O primeiro argumento é a posição inicial, o segundo a posição final.&lt;br /&gt;&lt;br /&gt;Quando precisamos procurar uma string dentro da outra, usamos o método &lt;b&gt;indexOf&lt;/b&gt;, esse método aceita uma string como argumento, e procura essa string dentro da string original, se encontrado retorna a posição onde foi encontrado, caso contrário retorna -1.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "abcde";&lt;br /&gt;&lt;br /&gt;alert(a.indexOf("b"));&lt;br /&gt;alert(a.indexOf("e"));&lt;br /&gt;alert(a.indexOf("cd"));&lt;br /&gt;alert(a.indexOf("z"));&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Também é possivel passar um segundo argumento, que indica a posição inicial da busca (sinta-se livre para testar). Inverso ao &lt;b&gt;indexOf&lt;/b&gt; que busca a partir do início da string, existe o método &lt;b&gt;lastIndexOf&lt;/b&gt; que procura do início para o começo da string.&lt;br /&gt;&lt;br /&gt;Esse não é o melhor método para buscar algo dentro de uma string, o melhor é usar expressões regulares (veremos isso mais adiante), mas para casos mais simples, o &lt;b&gt;indexOf&lt;/b&gt; resolve muitas coisas.&lt;br /&gt;&lt;br /&gt;O último método que veremos, é o método &lt;b&gt;split&lt;/b&gt;, esse método "quebra" uma string em um array, usando uma string para realizar essa quebra (fazendo a separação):&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "isso seria uma simples frase";&lt;br /&gt;var b = a.split(' '); //separando por espacos&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &lt; b.length; i++) {&lt;br /&gt; alert(b[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Esses foram os métodos principais para tratamento de string no JavaScript, não menos importante, temos a propriedade &lt;b&gt;length&lt;/b&gt; (isso, mesmo nome que tem no Array), o length retorna a quantidade de caracteres que existem na string.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = "abc";&lt;br /&gt;var b = "abcde";&lt;br /&gt;var c = "uma string cheia de caracteres";&lt;br /&gt;&lt;br /&gt;alert(a.length);&lt;br /&gt;alert(b.length);&lt;br /&gt;alert(c.length);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Expressões Regulares&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;As expressões regulares são a parte mais interessante da área de strings (pelo menos pra mim). Com expressões regulares você consegue facilmente validar strings, coisas que precisariam de um grande código se fossem feitas de outra maneira (como usando substrings e indexOf).&lt;br /&gt;&lt;br /&gt;O JavaScript tem um objeto chamado &lt;b&gt;RegExp&lt;/b&gt; que cuida dessa parte, existe o meio onde você cria um RegExp e valida uma string a partir dele, ou você pode usar um método da string (que é o &lt;b&gt;match&lt;/b&gt;) para usar um RegExp para validar, no final tudo gera o mesmo resultado. Vamos ver como validar uma data usando RegExp (vamos ver usando os 2 processos que eu disse):&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var dataValidator = new RegExp("^\\d{2}/\\d{2}/\\d{4}$");&lt;br /&gt;&lt;br /&gt;if(dataValidator.test('15/06/2006'))&lt;br /&gt; alert('Data válida');&lt;br /&gt;else&lt;br /&gt; alert('Data inválida');&lt;br /&gt; &lt;br /&gt;if(dataValidator.test('158/06/2006'))&lt;br /&gt; alert('Data válida');&lt;br /&gt;else&lt;br /&gt; alert('Data inválida');&lt;br /&gt; &lt;br /&gt;if('15/06/2006'.match(dataValidator))&lt;br /&gt; alert('Data válida');&lt;br /&gt;else&lt;br /&gt; alert('Data inválida');&lt;br /&gt; &lt;br /&gt;if('158/06/2006'.match(dataValidator))&lt;br /&gt; alert('Data válida');&lt;br /&gt;else&lt;br /&gt; alert('Data inválida');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Esse validador diz que a string deve ter 2 digitos numericos (&lt;b&gt;\d{2}&lt;/b&gt;), depois uma barra, mais dois digitos numericos, depois outra barra, e finalmente 4 digitos numericos. Também informamos que a string deve ser exatamente isso (usando o &lt;b&gt;^&lt;/b&gt; no início e &lt;b&gt;$&lt;/b&gt; no final), o digito &lt;b&gt;^&lt;/b&gt; diz que a string deve comecar daquele jeito, e o &lt;b&gt;$&lt;/b&gt; diz que a string deve acabar daquele jeito. Como eu disse antes, não vou parar para explicar as expressões regulares pois isso está fora do meu contexto.&lt;br /&gt;&lt;br /&gt;Além de validar, as vezes queremos pegar alguns pedaços da string, por exemplo, se a partir dessa string de mes, quizesse-mos pegar apenas o mês (que seriam os 2 dígitos do meio), com expressões regulares isso se torna facil, vamos ver isso no exemplo a seguir, e também vamos ver outro meio de iniciar expressões regulares:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var dataValidator = /^\d{2}\/(\d{2})\/\d{4}$/;&lt;br /&gt;var data = '15/12/2005';&lt;br /&gt;var grupos;&lt;br /&gt;&lt;br /&gt;if(grupos = data.match(dataValidator)) {&lt;br /&gt; alert('Mes: ' + grupos[1]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Percebam o novo modo de criação, você só precisa colocar uma &lt;b&gt;/&lt;/b&gt; e depois outra para finalizar, a expressão fica dentro das barras, quando é preciso inserir &lt;b&gt;/&lt;/b&gt; dentro da expressão usamas &lt;b&gt;\/&lt;/b&gt; assim estamos "escapando" a barra. Outra observação é que colocamos a parte da expressão que pega o mês entre parênteses, assim podemos recupera-la depois. Além de validar, o método &lt;b&gt;match&lt;/b&gt; retorna um array com os grupos que foram marcados dentro da expressão, o índice zero contém a string inteira, e a partir do um tem os grupos marcados (na mesma ordem em que foram marcados na string).&lt;br /&gt;&lt;br /&gt;Também podemos fazer substituições usando expressões regulares, por exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var string = 'mariazinha, joaninha, pedrinho';&lt;br /&gt;var novaString = string.replace(/(zinh(a|o)|inh)/g, '');&lt;br /&gt;&lt;br /&gt;alert(novaString);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;No caso substituimos as ocorrências expressão por nada :P. Notem agora o uso de uma letra "g" no final da expressão, essa letra "g" indica que mesmo após uma ocorrencia, ele deve continuar buscando a expressão na string, se você remover essa letra ele só vai substituir o nome de mariazinha. Fora a letra &lt;b&gt;g&lt;/b&gt; temos a letra &lt;b&gt;i&lt;/b&gt; que torna a expressão &lt;b&gt;case-insensitive&lt;/b&gt; (não diferencia maiúsculas de minúsculas) e a letra &lt;b&gt;m&lt;/b&gt; que faz buscas multi-linha.&lt;br /&gt;&lt;br /&gt;Por hoje é só pessoal, espero ter conseguido passar o básico de strings e uso de expressões regulares em JavaScript, estudem expressões regulares pelo site que eu passei no início do artigo, vocês vão ver coisas realmente interessantes, estudem la e vão testando a aplicação das mesmas com o JavaScript, assim vocês pegam um "2 em 1" ;)&lt;br /&gt;&lt;br /&gt;Antes de ir, sempre aquela boa referência:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Classe String&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;String (Built-in Object)&lt;/b&gt;&lt;br /&gt;String is the container object for the primitive string data type. It supplies methods for the manipulation of strings in addition to those that create traditional HTML markup from plain text. When manipulating strings, remember that like all JavaScript indices, the enumeration of character positions begins with zero.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new String(initialValue); &lt;br /&gt;&lt;br /&gt;where initialValue is a string. Omitting initialValue creates a String where value is the empty string ("").&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;length&lt;/b&gt; Integer indicating the number of characters in the string. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;anchor(name)&lt;/b&gt; Returns the string marked up as an HTML anchor (&amp;lt;a name="name"&gt;&lt;br /&gt;&lt;br /&gt;string value&amp;lt;/a&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1). &lt;br /&gt;&lt;br /&gt;&lt;b&gt;big()&lt;/b&gt; Returns the string marked up as big HTML text (&amp;lt;big&gt;string value&amp;lt;/big&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;blink()&lt;/b&gt; Returns the string marked up as blinking HTML text (&amp;lt;blink&gt;string value&amp;lt;/blink&gt;). (IE3+ (JScript 1.0+), N2+ (JavaScript 1.0+), MOZ)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;bold()&lt;/b&gt; Returns the string marked up as bold HTML text (&amp;lt;bold&gt;string value&amp;lt;/bold&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;charAt(position)&lt;/b&gt; Returns a string containing the character at index position in the string. The empty string is returned if position is out of range. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;charCodeAt(position)&lt;/b&gt; Returns an unsigned integer representing the Unicode value of the character at index position. If position is out of range, NaN is returned. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;concat(string2 [, string3 [, ... ]])&lt;/b&gt; Returns the string obtained by concatenating the current string value with string2, string3, .... (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;fixed()&lt;/b&gt; Returns the string marked up as fixed-width HTML text (&amp;lt;tt&gt;string value&amp;lt;/tt&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;fontcolor(theColor)&lt;/b&gt; Returns the string marked up as colored HTML according to the string color (&amp;lt;font color="theColor"&gt;string value&amp;lt;/font&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;fontsize(theSize)&lt;/b&gt; Returns the string marked up according to the HTML font size given in theSize (&amp;lt;font size="theSize"&gt;string value&amp;lt;/font&gt;). HTML font sizes are 1 through 7, or relative +/– 1–6. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;fromCharCode(char0 [, char1 [, ...]])&lt;/b&gt; Creates a string from the given characters. The arguments char0, char1, ... are Unicode numbers corresponding to the desired characters. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1, Static)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;indexOf(searchString [, startIndex])&lt;/b&gt; Returns the index of the first occurrence of searchString in the string. If startIndex is specified, then the first occurrence after index startIndex is returned. If searchString is not found, –1 is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;italics()&lt;/b&gt; Returns the string marked up as italicized HTML text (&amp;lt;i&gt;string value&amp;lt;/i&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lastIndexOf(searchString [, startIndex])&lt;/b&gt; Returns the index of the last occurrence of searchString in the string. If startIndex is specified, the index of the last occurrence starting at index startIndex or before is returned. If searchString is not found, –1 is returned. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;link(theHref)&lt;/b&gt; Returns the string marked up as an HTML link to the string theHref (&amp;lt;a href="theHref"&gt;string value&amp;lt;/a&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;match(regexp)&lt;/b&gt; Executes a regular expression match with the regular expression regexp and returns an array of results. If no match is found, null is returned. Otherwise, the returned array is exactly like that returned by RegExp.exec(). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;replace(regexp, replacement)&lt;/b&gt; Returns the string obtained by executing a match with the regular expression regexp on the string and then replacing each piece of matching text with the string replacement. In IE5.5 and N4.06+ replacement can be a function (see full description at MSDN). (IE3+ (JScript 1.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;search(regexp)&lt;/b&gt; Executes a regular expression match with regular expression regexp and returns the index of the beginning of the matching text in the string. If no match is found, –1 is returned. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;slice(start [, end])&lt;/b&gt; Returns a new string containing the substring from index start up to but not including index end. If end is omitted, the substring returned runs to the end of the string. If start or end is negative, it is treated as an offset from the end of the string. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;small()&lt;/b&gt; Returns the string marked up as small HTML text (&amp;lt;small&gt;string value&amp;lt;/small&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;split([separator [, limit]])&lt;/b&gt; Returns the array of strings obtained by splitting the string at each occurrence of separator (which may be a string or regular expression). The separator is not included in the array returned. If no separator is given, the string is split into an array of strings holding its individual characters. If the integer limit is given, only the first limit parts are placed in the array. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;strike()&lt;/b&gt; Returns the string marked up as struck-through HTML text (&amp;lt;strike&gt;string value&amp;lt;/strike&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;sub()&lt;/b&gt; Returns the string marked up as subscript HTML text (&amp;lt;sub&gt;string value&amp;lt;/sub&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;substr(start [, length])&lt;/b&gt; Returns a new string containing a substring of length length beginning at index start. If length is not given, the substring returned runs to the end of the string. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;substring(start [, end])&lt;/b&gt; Returns a new string containing the substring running from index start up to but not including index end. If end is not given, the substring runs to the end of the string. If start is greater than end, the values are swapped. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;sup()&lt;/b&gt; Returns the string marked up as superscript HTML text (&amp;lt;sup&gt;string value&amp;lt;/sup&gt;). (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toLowerCase()&lt;/b&gt; Returns the string converted to all lowercase. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toUpperCase()&lt;/b&gt; Returns the string converted to all uppercase. (IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE3+ (JScript 1.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Notes&lt;/b&gt;&lt;br /&gt;This object does not operate on values in place. That is, when manipulating a String with one of its methods, the method returns the result of the operation. It does not change the value of the String that it was invoked as a method of. You can, of course, use self-assignment to this effect—for example,&lt;br /&gt;&lt;br /&gt;var mystring = mystring.toUpperCase() &lt;br /&gt;&lt;br /&gt;The String methods do not produce XHTML style markup.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Classe RegExp&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal;"&gt;&lt;b&gt;RegExp (Built-in Object)&lt;/b&gt;&lt;br /&gt;Instances of RegExp objects hold regular expression patterns and provide the properties and methods that enable their use on strings. In addition, each window has a RegExp object that provides static (class) properties giving information about the most recent match that was executed. These properties are dynamically scoped.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new RegExp(expr [, flags]); &lt;br /&gt;&lt;br /&gt;where expr is a string containing a regular expression (for example, "abc.*") and flags is an optional string denoting the flags for the expression (for example, "gi").&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;$1, $2, ... $9&lt;/b&gt; The $n property contains the string corresponding to the nth parenthesized subexpression of the most recently executed match. The properties are read-only. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;global&lt;/b&gt; A read-only Boolean indicating whether the global flag ("g") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;ignoreCase&lt;/b&gt; A read-only Boolean indicating whether the case-insensitive flag ("i") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;index&lt;/b&gt; A read-only integer value indicating the character position where the first successful match begins (during the most recently executed match). (IE4+ (JScript 3.0+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;input&lt;/b&gt; Holds the string upon which the most recent regular expression match was conducted. This property is not automatically filled in N6. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lastIndex&lt;/b&gt; Integer specifying the character index of the string at which the next match will begin. Used during global matching. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lastMatch&lt;/b&gt; A read-only string containing the last matched characters of the most recent match. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;lastParen&lt;/b&gt; A read-only string containing the last matched parenthesized subexpression (of the most recent match). (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;leftContext&lt;/b&gt; A read-only substring up to but not including the beginning of the most recently matched text (of the most recently executed match). (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;multiline&lt;/b&gt; A read-only Boolean indicating whether the multiline flag ("m") was used to create the regular expression. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; Reference to the object’s prototype. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;rightContext&lt;/b&gt; A read-only substring following (but not including) the most recently matched text. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;source&lt;/b&gt; A read-only string containing the text that makes up the pattern (excluding any slashes used to define it and the flags). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;compile(expr [, flags]) Compiles the regular expression expr with flags flags in the object. Used to replace an expression with a new one. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;exec(str)&lt;/b&gt; Executes a match against the string str and returns an array containing the results. If no match was made, null is returned. If str is omitted, the contents of RegExp.input is used as str. The resulting array has the entire match in element zero, and any matched subexpressions at subsequent indices. It also has instance properties input (which holds the string on which the match was executed), index (which holds the index of the beginning of the match in the input string), and in IE lastIndex (which holds the index of the first character following the match). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;test(str)&lt;/b&gt; Returns a Boolean indicating whether the regular expression matches a part of the string str. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns the string corresponding to the regular expression, including enclosing slashes and any flags that were used to define it. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMAScript Edition 3.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Vou indo, no próximo artigo eu falarei sobre outros objetos Built-In, depois dele já começaremos a parte legal do JavaScript, me suportem até lá, vai valer a pena ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115887788767778688?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115887788767778688/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115887788767778688&amp;isPopup=true' title='14 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115887788767778688'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115887788767778688'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/strings-e-expresses-regulares.html' title='Strings e Expressões Regulares'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>14</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115835383242043238</id><published>2006-09-15T16:28:00.000-03:00</published><updated>2006-09-21T17:34:42.490-03:00</updated><title type='text'>Arrays</title><content type='html'>Agora vamos começar a estudar os objetos built-in do JavaScript, vamos comecar com um objeto muito importante, o objeto &lt;b&gt;Array&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;Como vocês devem saber, o &lt;b&gt;Array&lt;/b&gt; é uma estrutura de dados, no JavaScript essa é a única estrutura existente (por padrão), os arrays do JavaScript só podem ter índices númericos, na verdade você até pode usar índices associativos, mas na verdade você estará modificando o objeto e não colocando um dado no array. Vamos ver alguns exemplos simples de arrays no JavaScript.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = new Array();&lt;br /&gt;nomes[0] = 'Maria';&lt;br /&gt;nomes[1] = 'Joao';&lt;br /&gt;nomes[2] = 'Ana';&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Fizemos um simples array, colocamos uma &lt;b&gt;string&lt;/b&gt; em cada item do nosso array colocamos uma string, depois fizemos um &lt;b&gt;for&lt;/b&gt; que percorre os itens do nosso array. Note o uso da variável &lt;b&gt;length&lt;/b&gt; do array, essa variável nos retorna a quantidade atual de itens no array. Vamos ver outras formas para criar esse mesmo array:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = [];&lt;br /&gt;nomes[0] = 'Maria';&lt;br /&gt;nomes[1] = 'Joao';&lt;br /&gt;nomes[2] = 'Ana';&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = ['Maria', 'Joao', 'Ana'];&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = new Array('Maria', 'Joao', 'Ana');&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = [];&lt;br /&gt;nomes.push('Maria');&lt;br /&gt;nomes.push('Joao');&lt;br /&gt;nomes.push('Ana');&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Agora eu mostrei que podemos substituir o &lt;b&gt;new Array()&lt;/b&gt; por &lt;b&gt;[]&lt;/b&gt;, eles funcionam da mesma maneira, use o de sua preferência. Também vimos que é possivel inicializar um array já com valores, quando sabemos os valores isso é util, mas na maioria dos casos nós precisamos sair colocando valores ao longo do tempo, usando o método &lt;b&gt;push&lt;/b&gt; do array, nós inserimos um valor no final do array, podemos inserir varios valores usando apenas um push, como veremos abaixo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var nomes = [];&lt;br /&gt;nomes.push('Maria', 'Joao', 'Ana');&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; nomes.length; i++) {&lt;br /&gt; alert(nomes[i]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Os arrays do JavaScript são bastante dinâmicos, o mesmo array pode ter valores numéricos, strings, objetos e outros, tudo num mesmo array, o JavaScript não faz distinção. Os arrays em JavaScript tem métodos úteis para podermos usa-lo como uma &lt;b&gt;pilha&lt;/b&gt; ou &lt;b&gt;fila&lt;/b&gt; por exemplo.&lt;br /&gt;&lt;br /&gt;Vou falar rapidamente sobre os métodos mais usados do array:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt; &lt;li&gt;&lt;b&gt;push()&lt;/b&gt; - adiciona um ou mais itens ao final do array&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;b&gt;pop()&lt;/b&gt; - retorna e remove o último elemento do array&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;b&gt;shift()&lt;/b&gt; - retorna e remove o primeiro elemento do array&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;b&gt;unshift()&lt;/b&gt; - adiciona um ou mais itens no início do array&lt;/li&gt;&lt;br /&gt; &lt;li&gt;&lt;b&gt;join()&lt;/b&gt; - ele cola todos os elementos do array, usando uma string (passada por parâmetro) como separador, e retorna essa string&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;Vamos agora construir um programinha simples, que coleta dados de pessoas, armazena esses dados em um array, e depois gera um simples relatório. Vamos explicar melhor o nosso programa:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;1 - coleta de dados&lt;/b&gt;&lt;br /&gt;Usando o comando &lt;b&gt;prompt&lt;/b&gt; do JavaScript, vamos coletar dados de 10 pessoas, os dados coletados serão: nome, idade e sexo.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;2 - processamento de dados&lt;/b&gt;&lt;br /&gt;Vamos tratar nossos dados e conseguir as informações desejadas, nesse nosso caso, vamos mostrar ao final, o nome do homem mais velho e sua idade, o nome da mulher mais nova e sua idade, quantos homens e quantas mulheres foram entrevistados.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;3 - exibicao de dados&lt;/b&gt;&lt;br /&gt;Vamos mostrar os dados gerados na tela.&lt;br /&gt;&lt;br /&gt;Antes de começar, eu devo dizer que esta não é forma mais simples de fazer esse algorimo, mas minha intenção é mostrar mais recursos do array. Nessa forma, vamos olhar como fazer usando a função &lt;b&gt;sort&lt;/b&gt; do array.&lt;br /&gt;&lt;br /&gt;A primeira coisa a ser feita, é criar um objeto &lt;b&gt;Pessoa&lt;/b&gt;, que vai ser uma estrura que irá guardar os dados de cada entrevistado:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var Pessoa = function(nome, idade, sexo) {&lt;br /&gt; this.nome = nome;&lt;br /&gt; this.idade = idade;&lt;br /&gt; this.sexo = sexo;&lt;br /&gt;};&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Bem simples, apenas um objeto que guarda os dados que precisamos. Vamos agora definir as variáveis que farão parte do programa:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var numPessoas = 5;&lt;br /&gt;var homens = [];&lt;br /&gt;var mulheres = [];&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;A variável &lt;b&gt;numPessoas&lt;/b&gt; vai dizer quantas pessoas serão entrevistas, no array &lt;b&gt;homens&lt;/b&gt; vamos guardas os entrevistados do sexo masculino, e no array &lt;b&gt;mulheres&lt;/b&gt; os do sexo feminino .&lt;br /&gt;&lt;br /&gt;Vamos agora fazer a primeira parte, a coleta de dados:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;for(var i = 0; i &amp;lt; numPessoas; i++) {&lt;br /&gt; var nome = prompt('Digite o nome:');&lt;br /&gt; var idade = prompt('Digite a idade:');&lt;br /&gt; var sexo = prompt('Digite o sexo (M para masculino, F para feminino):');&lt;br /&gt; &lt;br /&gt; idade = parseInt(idade); //convertendo a string em numero&lt;br /&gt; sexo = sexo.toUpperCase(); //convertendo para maiusculo&lt;br /&gt; &lt;br /&gt; var p = new Pessoa(nome, idade, sexo);&lt;br /&gt; &lt;br /&gt; if(sexo == 'M')&lt;br /&gt;  homens.push(p);&lt;br /&gt; else&lt;br /&gt;  mulheres.push(p);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Pronto, com isso ja teremos os nossos arrays preenchidos. Para usarmos a função sort num objeto como o nosso, precisaremos criar uma função separada que vai definir quando um objeto é superior, inferior ou igual ao outro, vamos criar essa função:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var PessoaIdadeSorter = function(obj1, obj2) {&lt;br /&gt; if(obj1.idade == obj2.idade)&lt;br /&gt;  return 0;&lt;br /&gt; &lt;br /&gt; return obj1.idade &gt; obj2.idade ? 1 : -1;&lt;br /&gt;};&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;A função compara a idade das pessoas, e retorna o valor de acordo. Agora basta classificarmos nossos arrays:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;homens.sort(PessoaIdadeSorter);&lt;br /&gt;mulheres.sort(PessoaIdadeSorter);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Pronto, nossos arrays já estão classificados por idade, agora é facil terminar, vamos fazer a exibição:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var qtdHomens = homes.length;&lt;br /&gt;var qtdMulheres = mulheres.length;&lt;br /&gt;var homemMaisVelho = homens.pop();&lt;br /&gt;var mulherMaisNova = mulheres.shift();&lt;br /&gt;&lt;br /&gt;document.write('Foram entrevistados ' + qtdHomens + ' homens e ' + qtdMulheres + ' mulheres.&lt;br /&gt;');&lt;br /&gt;document.write('O homem mais velho se chama ' + homemMaisVelho.nome + ' com ' + homemMaisVelho.idade + ' anos&lt;br /&gt;');&lt;br /&gt;document.write('A mulher mais nova se chama ' + mulherMaisNova.nome + ' com ' + mulherMaisNova.idade + ' anos&lt;br /&gt;');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como nossos arrays estão ordenados pela idade, então o homem mais velho é o ultimo elemento do array homens, e a mulher mais nova é o primeiro elemento do array das mulheres.&lt;br /&gt;&lt;br /&gt;Vou colocar o código completo abaixo (só pra facilitar):&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var Pessoa = function(nome, idade, sexo) {&lt;br /&gt; this.nome = nome;&lt;br /&gt; this.idade = idade;&lt;br /&gt; this.sexo = sexo;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var numPessoas = 5;&lt;br /&gt;var homens = [];&lt;br /&gt;var mulheres = [];&lt;br /&gt;&lt;br /&gt;for(var i = 0; i &amp;lt; numPessoas; i++) {&lt;br /&gt; var nome = prompt('Digite o nome:');&lt;br /&gt; var idade = prompt('Digite a idade:');&lt;br /&gt; var sexo = prompt('Digite o sexo (M para masculino, F para feminino):');&lt;br /&gt; &lt;br /&gt; idade = parseInt(idade); //convertendo a string em numero&lt;br /&gt; sexo = sexo.toUpperCase(); //convertendo para maiusculo&lt;br /&gt; &lt;br /&gt; var p = new Pessoa(nome, idade, sexo);&lt;br /&gt; &lt;br /&gt; if(sexo == 'M')&lt;br /&gt;  homens.push(p);&lt;br /&gt; else&lt;br /&gt;  mulheres.push(p);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var PessoaIdadeSorter = function(obj1, obj2) {&lt;br /&gt; if(obj1.idade == obj2.idade)&lt;br /&gt;  return 0;&lt;br /&gt; &lt;br /&gt; return obj1.idade &gt; obj2.idade ? 1 : -1;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;homens.sort(PessoaIdadeSorter);&lt;br /&gt;mulheres.sort(PessoaIdadeSorter);&lt;br /&gt;&lt;br /&gt;var qtdHomens = homes.length;&lt;br /&gt;var qtdMulheres = mulheres.length;&lt;br /&gt;var homemMaisVelho = homens.pop();&lt;br /&gt;var mulherMaisNova = mulheres.shift();&lt;br /&gt;&lt;br /&gt;document.write('Foram entrevistados ' + qtdHomens + ' homens e ' + qtdMulheres + ' mulheres.&lt;br /&gt;');&lt;br /&gt;document.write('O homem mais velho se chama ' + homemMaisVelho.nome + ' com ' + homemMaisVelho.idade + ' anos&lt;br /&gt;');&lt;br /&gt;document.write('A mulher mais nova se chama ' + mulherMaisNova.nome + ' com ' + mulherMaisNova.idade + ' anos&lt;br /&gt;');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Com isso eu termino os arrays, vou a referência do objeto Array para quem tiver interesse:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;b&gt;Array (Built-in Object)&lt;/b&gt;&lt;br /&gt;Arrays store ordered lists of data. Data is stored at indices enumerated beginning with zero, which are accessed using the array access ([]) operator. Allocation of array memory is handled by the interpreter, so there is no need to explicitly resize arrays to accommodate more data. In addition, arrays are permitted to be sparse, that is, to have “holes” consisting of an arbitrary number of unused indices. Any index that has not been assigned data has value undefined, and the highest index addressable is 232 –1 because indices are converted to unsigned 32-bit integers before use. JavaScript arrays are one-dimensional, but since array elements can be of any type, multidimensional arrays are supported as arrays with elements that are arrays.&lt;br /&gt;&lt;br /&gt;You can explicitly remove a value from an array using the delete operator, but there is no way to destroy an array other than by setting the variable that holds its reference to null.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new Array([ val1 [, val2 [, val3 ... ] ] ]); &lt;br /&gt;&lt;br /&gt;where the comma-separated values are treated as initial values for array indices 0, 1, 2, and so on. The exception is if a single numeric parameter is supplied, in which case the array’s length property is set to this value.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;constructor Reference to the constructor object, which created the object. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;length&lt;/b&gt; Numeric value indicating the next empty index at the end of the array (not the number of elements in the array). Setting this property to a value less than its current value will undefine any elements with index &gt;= length. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; Reference to the object’s prototype. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;concat([item1 [, item2 [, ...]]])&lt;/b&gt; Appends the comma-separated list of items to the end of the array and returns the new array (it does not operate on the array in place). If any item is an array, its first level is flattened (that is, the item’s elements are appended each as a separate element). (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;join([separator])&lt;/b&gt; Returns the string obtained by concatenating all the array’s elements. If the string separator is supplied, separator will be placed between adjacent elements. The separator defaults to a comma. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;pop()&lt;/b&gt; Removes the last element of the array and returns it. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;push([item1 [, item2 [, ...]]])&lt;/b&gt; Appends the parameters (in order) to the end of the array and returns the new length. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;reverse()&lt;/b&gt; Reverses the order of the elements (in place). (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;shift()&lt;/b&gt; Removes the first element from the array, returns it, and shifts all other elements down one index. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;slice(begin [, end])&lt;/b&gt; Returns a new array containing the elements from index begin up to but not including index end. If end is omitted, all elements to the end of the array are extracted. If end is negative, it is treated as an offset from the end of the array. (IE4+ (JScript 3.0+), MOZ, N4+ (JavaScript 1.2), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;sort([compareFunc])&lt;/b&gt; Sorts the array in place in lexicographic order. The optional argument compareFunc is a function that can change the behavior of the sort. It will be passed two elements and should return a negative value if the first element is less than the second, a positive value if the second is less than the first, or zero if they are equal. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;splice(start, howMany [, item1 [, item2 [, ...]]])&lt;/b&gt; Removes howMany elements from the array beginning at index start and replaces the removed elements with the itemN arguments (if passed). An array containing the deleted elements is returned. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns a string containing the comma-separated list of elements. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;unshift([item1 [, item2 [, ...]]])&lt;/b&gt; Inserts the items (in order) at the front of the array, shifting existing values up to higher indices. (IE5.5+ (JScript 5.5+), MOZ, N4+ (JavaScript 1.2+), ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;valueOf()&lt;/b&gt; Same as toString(). (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE4+ (JScript 2.0+), Mozilla, N3+ (JavaScript 1.1+), ECMAScript Edition 1.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Notes&lt;/b&gt;&lt;br /&gt;In Netscape 4.0–4.05 (JavaScript 1.2) a single numeric parameter to the constructor is added to the single array element—it is not treated as an initial value for length.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Por hoje é tudo, no próximo artigo eu irei falar sobre o objeto &lt;b&gt;String&lt;/b&gt;. E plz, comentem, seu comentário é muito importante ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115835383242043238?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115835383242043238/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115835383242043238&amp;isPopup=true' title='28 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115835383242043238'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115835383242043238'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/arrays.html' title='Arrays'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>28</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115800933951330072</id><published>2006-09-11T18:14:00.000-03:00</published><updated>2006-09-29T12:03:06.216-03:00</updated><title type='text'>Estruturas de Controle e Objetos</title><content type='html'>Como dito no artigo anterior, hoje iremos ver as estruturas de controle do JavaScript e vamos iniciar os estudos a programação orientada a objetos em JavaScript. Como eu disse antes, não tenho interção de ensinar lógica aqui, por isso irei apenas deixar alguns exemplos comentados usando as estruturas de controle, mandem e-mail ou comentários em caso de dúvidas.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Estrutura &lt;i&gt;if&lt;/i&gt; e estrura &lt;i&gt;else&lt;/i&gt;:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 3;&lt;br /&gt;var b = 5;&lt;br /&gt;var c = 3;&lt;br /&gt;&lt;br /&gt;if(a &lt; b) { //se a for menor que b&lt;br /&gt; alert('"a" é menor que "b"');&lt;br /&gt;} else { //caso contrario&lt;br /&gt; alert('"a" não é menor que "b"');&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;if(a == c) { //se a for igual a c&lt;br /&gt; alert('"a" é igual a "c"');&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Estrutura &lt;i&gt;switch case&lt;/i&gt;:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 3;&lt;br /&gt;&lt;br /&gt;switch(a) {&lt;br /&gt; case 1: //se a for 1&lt;br /&gt;  alert('"a" é 1');&lt;br /&gt;  break;&lt;br /&gt; case 2: //se a for 2&lt;br /&gt;  alert('"a" é 2');&lt;br /&gt;  break;&lt;br /&gt; case 3: //se a for 3&lt;br /&gt;  alert('"a" é 3');&lt;br /&gt;  break;&lt;br /&gt; case 4: //se a for 4&lt;br /&gt;  alert('"a" é 4');&lt;br /&gt;  break;&lt;br /&gt; default: //se a nao for nenhum dos casos, entao use o padrao&lt;br /&gt;  alert('"a" não está em nenhum dos outros valores');&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Lembrando que o &lt;b&gt;switch case&lt;/b&gt; do JavaScript também aceita valores de string, exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 'pessoa';&lt;br /&gt;&lt;br /&gt;switch(a) {&lt;br /&gt; case 'pessoa':&lt;br /&gt;  alert('anda sobre 2 pernas');&lt;br /&gt;  break;&lt;br /&gt; case 'cachorro':&lt;br /&gt;  alert('anda sobre 4 pernas');&lt;br /&gt;  break;&lt;br /&gt; case 'passaro':&lt;br /&gt;  alert('voa');&lt;br /&gt;  break;&lt;br /&gt; default:&lt;br /&gt;  alert('desconhecido');&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Estrutura &lt;i&gt;while&lt;/i&gt;:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 1;&lt;br /&gt;&lt;br /&gt;while(a &lt; 10) {&lt;br /&gt; alert(a + ' vezes');&lt;br /&gt; a++;&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Estrutura &lt;i&gt;for&lt;/i&gt;:&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;for(var i = 0; i &lt; 10; i++) {&lt;br /&gt; alert('ciclo ' + i);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Ainda existe outra estrutura para o &lt;b&gt;for&lt;/b&gt;, que é o chamado &lt;b&gt;for in&lt;/b&gt;, vamos ver isso ainda nesse artigo mais adiante.&lt;br /&gt;&lt;br /&gt;Temos a estrutura &lt;b&gt;with&lt;/b&gt; mas também deixaremos ela mais para frente.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Objetos&lt;/b&gt;&lt;br /&gt;Vamos agora iniciar nossos estudos quanto a criação de objetos com JavaScript. Como dito antes, tudo em JavaScript são objetos, você as vezes cria objetos e os usa sem nem se dar conta disso, vamos ver 2 maneiras de iniciar um objeto em branco:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var meuObjeto = new Object();&lt;br /&gt;var outroObject = {};&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Use qual você preferir, eu prefiro a segunda porque assim eu escrevo menos :P&lt;br /&gt;Agora temos incríveis objetos em branco que não fazem nada!! Não é maravilhoso?&lt;br /&gt;Brincadeiras de lado, em JavaScript todos os objetos são dinâmicos, ou seja, eu posso adicionar recursos a eles a qualquer hora, criar variáveis e métodos que nunca existiram nele, podemos mudar isso apenas no objeto atual, ou podemos modificar o seu &lt;b&gt;prototype&lt;/b&gt;, modificando o &lt;b&gt;prototype&lt;/b&gt; nós podemos adicionar variáveis e métodos para todas as instâncias de um objeto. Vamos então criar nosso primeiro objeto útil:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var Circunferencia = function() {};&lt;br /&gt;Circunferencia.prototype.raio = 1; //valor padrao&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.diametro = function() {&lt;br /&gt; return this.raio * 2;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.perimetro = function() {&lt;br /&gt; return 2 * Math.PI * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.area = function() {&lt;br /&gt; return Math.PI * this.raio * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var b = new Circunferencia();&lt;br /&gt;&lt;br /&gt;b.raio = 5;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;br /&gt;&lt;br /&gt;b.raio = 7;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;br /&gt;&lt;br /&gt;b.raio = 10;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;O objeto para ter seu prototype modificado precisa iniciar-se a partir de uma função, os objetos que sao iniciados das outras formas servem mais como estruturas de dados, para transferir informações.&lt;br /&gt;&lt;br /&gt;Temos acima um simples objeto &lt;b&gt;Circunferencia&lt;/b&gt; que tem a variável &lt;b&gt;raio&lt;/b&gt; e os métodos &lt;b&gt;diametro()&lt;/b&gt;, &lt;b&gt;perimetro()&lt;/b&gt; e &lt;b&gt;area&lt;/b&gt;. Nós estamos adicionando esses métodos no objeto &lt;b&gt;prototype&lt;/b&gt; dentro da nossa classe, isso porque quando mudamos o prototype, nós alteramos a classe propriamente dita, então todas as instâncias de bola terão esses métodos/variáveis. Veja que quando estamos dentro de um método e queremos acessar outros recursos da classe, temos que colocar o &lt;b&gt;this&lt;/b&gt; seguido de um &lt;b&gt;.&lt;/b&gt; para termos a referencia dessas variáveis/métodos. Alguns agora podem estar se perguntando: "e como eu faço pra criar um inicializador para minha classe?". Ai é só colocar-mos algo na função de criação, assim ela se torna o inicializador, vamos ver isso:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var Circunferencia = function(raio) {&lt;br /&gt; this.raio = raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.diametro = function() {&lt;br /&gt; return this.raio * 2;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.perimetro = function() {&lt;br /&gt; return 2 * Math.PI * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.area = function() {&lt;br /&gt; return Math.PI * this.raio * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var b = new Circunferencia(5);&lt;br /&gt;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;br /&gt;&lt;br /&gt;b.raio = 7;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;br /&gt;&lt;br /&gt;b.raio = 10;&lt;br /&gt;alert(b.diametro());&lt;br /&gt;alert(b.perimetro());&lt;br /&gt;alert(b.area());&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Simples não? Na verdade não estamos criando exatamente um objeto novo, e sim modificando um objeto do tipo &lt;b&gt;function&lt;/b&gt;, parece meio louco, mas logo logo você se acostuma.&lt;br /&gt;&lt;br /&gt;Antes de terminarmos vamos usar nosso exemplo anterior para demostrar o uso de &lt;b&gt;for in&lt;/b&gt; e &lt;b&gt;with&lt;/b&gt;:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var Circunferencia = function(raio) {&lt;br /&gt; this.raio = raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.diametro = function() {&lt;br /&gt; return this.raio * 2;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.perimetro = function() {&lt;br /&gt; return 2 * Math.PI * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;Circunferencia.prototype.area = function() {&lt;br /&gt; return Math.PI * this.raio * this.raio;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var b = new Circunferencia(5);&lt;br /&gt;&lt;br /&gt;with(b) {&lt;br /&gt; alert(diametro());&lt;br /&gt; alert(perimetro());&lt;br /&gt; alert(area());&lt;br /&gt;&lt;br /&gt; raio = 7;&lt;br /&gt; alert(diametro());&lt;br /&gt; alert(perimetro());&lt;br /&gt; alert(area());&lt;br /&gt;&lt;br /&gt; raio = 10;&lt;br /&gt; alert(diametro());&lt;br /&gt; alert(perimetro());&lt;br /&gt; alert(area());&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;for(var p in b) {&lt;br /&gt; alert(p + ' ==&gt; ' + b[p]);&lt;br /&gt;}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como vimos acima, o &lt;b&gt;with&lt;/b&gt; é usado para manter um objeto quando ele vai ser muito usado, assim sempre que apontar-mos as coisas, é como se já estivemos avisando que estão na variável que definimos no &lt;b&gt;with&lt;/b&gt;. Já o &lt;b&gt;for in&lt;/b&gt; serve para passarmos por tudo que tem dentro de um objeto, dizemos o nome da chave (&lt;b&gt;p&lt;/b&gt; no nosso caso) &lt;b&gt;in&lt;/b&gt; e o nome da variável, assim como se fosse um array associativo, podemos pegar os métodos/variáveis de um objeto passando seu nome dentro de cochetes.&lt;br /&gt;&lt;br /&gt;Segue agora a referêcia do Object, todos os objetos do JavaScript contém os métodos e propriedades citadas abaixo:&lt;br /&gt;&lt;br /&gt;&lt;code style="white-space: normal"&gt;&lt;b&gt;Object (Built-in Object)&lt;/b&gt;&lt;br /&gt;Object is the basic object from which all other objects are derived. It defines methods common to all objects that are often overridden to provide functionality specific to each object type. For example, the Array object provides a toString() method that functions as one would expect an array’s toString() method to behave.This object also permits the creation of user-defined objects and instances are quite often used as associative arrays.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt;var instanceName = new Object(); &lt;br /&gt;&lt;br /&gt;This statement creates a new (generic) object.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; The prototype for the object. This object defines the properties and methods common to all objects of this type. (IE4+ (JScript 3.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;hasOwnProperty(property)&lt;/b&gt; Returns a Boolean indicating whether the object has an instance property by the name given in the string property. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;isPrototypeOf(obj)&lt;/b&gt; Returns a Boolean indicating if the object referenced by obj is in the object’s prototype chain. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;propertyIsEnumerable(property)&lt;/b&gt; Returns a Boolean indicating if the property with the name given in the string property will be enumerated in a for/in loop. (IE5.5+, MOZ/N6+, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toSource()&lt;/b&gt; Returns a string containing a JavaScript literal that describes the object. (MOZ, N4.06+ (JavaScript 1.3+)) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns the object a string, by default "[object Object]". Very often overridden to provide specific functionality. (IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;unwatch(property)&lt;/b&gt; Disables watching of the object’s property given by the string property. (N4 (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;valueOf()&lt;/b&gt; Returns the primitive value associated with the object, by default the string "[object Object]". Often overridden to provide specific functionality. (IE4+ (JScript 3.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;watch(property, handler)&lt;/b&gt; Sets a watch on the object’s property given in string property. Whenever the value of the property changes, the function handler is invoked with three arguments: the name of the property, the old value, and the new value it is being set to. The handler can override the setting of the new value by returning a value, which is set in its place. (N4 (JavaScript 1.2))&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE4+ (JScript 3.0+), MOZ, N2+ (JavaScript 1.0+), ECMAScript Edition 1.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Por hoje é tudo, como já sabem: dúvidas, críticas, sugestões, podem me mandar um e-mail (wilkerlucio@gmail.com) ou deixem um comentário ;)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115800933951330072?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115800933951330072/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115800933951330072&amp;isPopup=true' title='4 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800933951330072'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800933951330072'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/estruturas-de-controle-e-objetos.html' title='Estruturas de Controle e Objetos'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115800911575729734</id><published>2006-09-11T18:11:00.000-03:00</published><updated>2006-09-11T18:11:55.986-03:00</updated><title type='text'>Funções com mais detalhes</title><content type='html'>Vamos hoje dar continuidade aos nossos estudos, hoje eu vou falar mais sobre escopo, vou falar sobre oque são objetos em JavaScript (calma, criação e implementação de objetos vai ficar pra outro dia, hoje vamos só entender o conceito do que é um objeto em JavaScript) e também vamos aprofundar o estudo de funções.&lt;br /&gt;&lt;br /&gt;Antes de continuarmos eu gostaria de dizer que eu não estou tentando ensinar lógica de programação, esses artigos são voltados a pessoas que já sabem lógica de programação, oque eu pretendo passar aqui é como usar a linguagem JavaScript.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Escopo e Objetos, a relação existente&lt;/b&gt;&lt;br /&gt;No artigo passado nós vimos um pouco sobre o escopo das variáveis, vimos a diferença entre uma variável global e uma variável criada internamente para uma função, agora vamos entender melhor oque realmente acontece.&lt;br /&gt;&lt;br /&gt;Em JavaScript, praticamente tudo (apenas com a excessão de tipos primitivos) são objetos, isso mesmo, uma &lt;b&gt;string&lt;/b&gt; é um objeto, um &lt;b&gt;array&lt;/b&gt;(falaremos sobre arrays em outros artigos) é um objeto, até mesmo uma função é um objeto no JavaScript.&lt;br /&gt;&lt;br /&gt;Os escopos sempre são relativos aos objetos, para uma variável existir, ela tem que estar dentro de um objeto, e esse objeto é o seu escopo, como eu disse antes, o escopo global é o objeto &lt;b&gt;window&lt;/b&gt;, quando você declara uma &lt;b&gt;var&lt;/b&gt; dentro de uma função, você está criando uma variável no escopo daquela função, mais a frente ainda nesse artigo eu mostrarei outras formas de criar funções, e vocês verão que uma função pode ser tratada da mesma forma que uma variável.&lt;br /&gt;&lt;br /&gt;Com isso eu termino minha explicação sobre escopo, mas a melhor forma de realmente entender isso é fazendo na prática, eu recomendo que vocês façam testes pra ver oque acontece com uma variável em diferentes escopos, porque essa é a melhor forma de enteder isso.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Funções, conhecendo-as melhor&lt;/b&gt;&lt;br /&gt;Nós ja aprendemos a criar funções, a passar parâmetros para a mesma e também como retornar dados, hoje vamos explorar melhor o conceito de funções em JavaScript e também vamos aprender a usar mais recurso das funções em JavaScript.&lt;br /&gt;&lt;br /&gt;Primeiro eu quero que fique bem claro para todos: "Funções de JavaScript são objetos".&lt;br /&gt;Exatamente, pra quem entender de oop, eu poderia dizer que a propria função do javascript já contem seus métodos e variáveis internas, ela realmente é um objeto e deve ser tratada como tal, vamos ver uma outra forma de criar uma função, usando essa forma fica mais claro o conceito de que ela é um objeto:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var minhaFuncao = function() {&lt;br /&gt; alert('funcao criada com sintaxe de variavel');&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;minhaFuncao();&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como podemos ver, essa sintaxe parece que estamos criando uma variável, mas estamos criando uma função. Optar por usar esse modo ou o outro que vimos anteriormente é uma questão de gosto, mas existe casos que só é possivel criar dessa 2 forma, eu sinceramente prefiro essa sintaxe mostrada acima, pois nela temos uma melhor controle sobre qual escopo a função está sendo criada.&lt;br /&gt;&lt;br /&gt;obs: note que quando usamos essa sintaxe, colocamos um ponto e vírgula (;) após a criação dela, essa é a sintaxe correta, pois estamos declarando uma variável, e sempre depois de uma declaração tem que vir um ponto e vírgula.&lt;br /&gt;&lt;br /&gt;As vezes nós criamos uma função sobre um escopo, mas precisamos que ela seja executada sobre um escopo diferente, entao como fazer isso? Como mudar o escopo da função?&lt;br /&gt;&lt;br /&gt;Em JavaScript isso é facil, como eu disse, funções são objetos, e elas tem seus métodos, uma função pode ser chamada de 3 formas diferentes, vamos ve-las:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var soma = function(a, b) {&lt;br /&gt; var resultado = a + b;&lt;br /&gt; alert('Resultado da soma: ' + resultado);&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;soma(2, 3); //essa é a forma que estamos usando, apenas diz o nome da funcao e acresce de ()&lt;br /&gt;soma.call(this, 2, 3); //esse é outro modo de chamar a função&lt;br /&gt;soma.apply(this, [2, 3]); //e temos também esse terceiro&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Vamos agora entender a diferença entre esses 3 modos:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;soma(2, 3)&lt;/b&gt; =&gt; esse é o método padrão, a função será executada no escopo de onde ela foi chamada, e os argumentos são passados normalmente.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;soma.call(this, 2, 3)&lt;/b&gt; =&gt; esse é muito parecido com o padrão, dizemos o nome da função e chamados o método &lt;b&gt;call&lt;/b&gt; da mesma, a única diferença se dá no primeiro argumento, o primeiro argumento não será passado, ao invéz disso, o primeiro argumento informa em qual escopo a função deve ser executada, usando &lt;b&gt;this&lt;/b&gt; mandamos executar no escopo atual, e nesse caso não existe diferença entre esse modo e o padrão.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;soma.apply(this, [2, 3])&lt;/b&gt; =&gt; esse quase igual ao anterior, o primeiro argumento funciona da mesma forma (para expecificar o escopo) mas temos diferenca na hora de passar os argumentos para a função. No lugar de passar os argumentos separados por vírgula, oque passamos é um &lt;b&gt;array&lt;/b&gt; contendo todos os argumentos, essa forma é mais dinâmica que as outras.&lt;br /&gt;&lt;br /&gt;obs: quando usamos [] estamos nos referindo a &lt;b&gt;arrays&lt;/b&gt;, vamos entender isso melhor em futuros artigos.&lt;br /&gt;&lt;br /&gt;Vamos agora aprender a usar parâmetros não definidos nas funções.&lt;br /&gt;Imagine que você queria uma função que some todos os parâmetros que forem passados para a mesma, mas você não sabe quantos parâmetros serão passados para essa função, para resolver esse problema, usaremos uma variável que é definida internamente pelo objeto da função, a variável &lt;b&gt;arguments&lt;/b&gt;.&lt;br /&gt;&lt;br /&gt;A variável &lt;b&gt;arguments&lt;/b&gt; é definida automaticamente em qualquer função, ela é um &lt;b&gt;array&lt;/b&gt; que contém todos os parâmetros passados para a função, vamos criar nossa função que soma todos os argumentos passados, assim veremos seu uso:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var somaTudo = function() {&lt;br /&gt; var total = 0; //iniciando a variavel que vai guardar o valor das somas&lt;br /&gt;&lt;br /&gt; for(var i = 0; i &lt; arguments.length; i++) {&lt;br /&gt;  total += arguments[i]; //adicionando valor na variavel total&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; return total;&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;alert(somaTudo(3, 2, 4, 8));&lt;br /&gt;alert(somaTudo(4, 5, 1, 3, 9, 6, 13));&lt;br /&gt;alert(somaTudo());&lt;br /&gt;alert(somaTudo(10));&lt;br /&gt;alert(somaTudo(3, 2, 1, 5, 6, 7));&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Viram como é simples o uso da variável &lt;b&gt;arguments&lt;/b&gt;?&lt;br /&gt;&lt;br /&gt;Para finalizar, vou deixar aqui uma referência (em inglês) do objeto Function, assim vocês podem ir testando seus métodos e variáveis, e lembrem-se sempre, a melhor maneira de aprender é fazendo, façam testes por ai, eu não tive tempo pra passar exercícios, mas futuramente eu estarei passando exercícios para vocês tentarem resolver, segue a referência:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;b&gt;Function (Built-in Object)&lt;/b&gt;&lt;br /&gt;Function is the object from which JavaScript functions are derived. Functions are first-class data types in JavaScript, so they may be assigned to variables and passed to functions as you would any other piece of data. Functions are, of course, reference types.&lt;br /&gt;&lt;br /&gt;The Function object provides both static properties like length and properties that convey useful information during the execution of the function, for example, the arguments[] array.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Constructor&lt;/b&gt;&lt;br /&gt; var instanceName = new Function([arg1 [, arg2 [, ...]] ,] body); &lt;br /&gt;&lt;br /&gt;The body parameter is a string containing the text that makes up the body of the function. The optional argN’s are the names of the formal parameters the function accepts. For example:&lt;br /&gt;&lt;br /&gt;var myAdd = new Function("x", "y", "return x + y");&lt;br /&gt;var sum = myAdd(17, 34);&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Properties&lt;/b&gt;&lt;br /&gt;&lt;b&gt;arguments[]&lt;/b&gt; An implicitly filled and implicitly available (directly usable as "arguments" from within the function) array of parameters that were passed to the function. This value is null if the function is not currently executing. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;arguments.callee&lt;/b&gt; Reference to the current function. This property is deprecated. (N4+, MOZ, IE5.5+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;arguments.caller&lt;/b&gt; Reference to the function that invoked the current function. This property is deprecated. (N3, IE4+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;arguments.length&lt;/b&gt; The number of arguments that were passed to the function. (IE4+ (JScript 2.0+), MOZ, N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;arity&lt;/b&gt; Numeric value indicating how many arguments the function expects. This property is deprecated. (N4+, MOZ)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;caller&lt;/b&gt; Reference to the function that invoked the current function or null if called from the global context. (IE4+ (JScript 2.0+), MOZ, N3+)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;constructor&lt;/b&gt; Reference to the constructor object that created the object. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;length&lt;/b&gt; The number of arguments the function expects to be passed. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;prototype&lt;/b&gt; Reference to the object’s prototype. (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Methods&lt;/b&gt;&lt;br /&gt;&lt;b&gt;apply(thisArg [, argArray])&lt;/b&gt; Invokes the function with the object referenced by thisArg as its context (so references to this in the function reference thisArg). The optional parameter argArray contains the list of parameters to pass to the function as it is invoked. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 3) &lt;br /&gt;&lt;br /&gt;&lt;b&gt;call(thisArg [, arg1 [, arg2 [, ...]]])&lt;/b&gt; Invokes the function with the object referenced by thisArg as its context (so references to this in the function reference thisArg). The optional parameters argN are passed to the function as it is invoked. (IE5.5+ (JScript 5.5+), N4.06+ (JavaScript 1.3+), MOZ, ECMA Edition 3)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;toString()&lt;/b&gt; Returns the string version of the function source. The body of built-in and browser objects will typically be represented by the value "[native code]". (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;valueOf()&lt;/b&gt; Returns the string version of the function source. The body of built-in and browser objects will typically be represented by the value "[native code]". (IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMA Edition 1)&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Support&lt;/b&gt;&lt;br /&gt;Supported in IE4+ (JScript 2.0+), N3+ (JavaScript 1.1+), MOZ, ECMAScript Edition 1.&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Por hoje é tudo, no próximo artigos falaremos sobre estruturas de controle e objetos, com isso iremos finalizar o "core" do JavaScript, e depois começaremos a falar dos objetos &lt;b&gt;Built-In&lt;/b&gt; (Array, Date, String...).&lt;br /&gt;&lt;br /&gt;Grato a atenção de todos.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115800911575729734?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115800911575729734/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115800911575729734&amp;isPopup=true' title='1 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800911575729734'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800911575729734'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/funes-com-mais-detalhes.html' title='Funções com mais detalhes'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-34235652.post-115800897949430990</id><published>2006-09-11T18:07:00.000-03:00</published><updated>2006-09-11T18:09:39.516-03:00</updated><title type='text'>Conceitos, Variáveis e Funções</title><content type='html'>Olá, bem vindo a esse blog. Esse é meu primeiro post nesse blog, comecarei dando noções básicas de Javascript. O objetivo desse blog eh passar informações desde o básico até o avançado sobre Javascript, o Javascript está sendo muito difundido na web e muitas pessoas não estão conseguindo acompanhar esse progresso devido a não ter a base do Javascript. Como eu disse antes, eu vou comecar as coisas do básico, mesmo que você ja saiba Javascript eu recomendaria que você desse uma lida nesses posts, porque as vezes umas coisas bestas passam despercebidas, mas essas besteiras podem fazer uma grande diferenca quando chega a hora da aplicação final.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Um pouco de história&lt;/b&gt;&lt;br /&gt;O Javascript foi criado pela Netspace em 1995 e era chamado inicialmente de LiveScript, depois ele passou a ter o nome JavaScript. No Internet Explorer, o nome da linguagem é JScript, eles a chamam assim para dizer que não é a mesma coisa, e realmente não é, e devido a isso é que temos os problemas de incompatibilidade entre o script nos browsers, o JScript tem muitos recursos que não existem no JavaScript, mas como no mundo atual em 98% dos casos (isso tira apenas os casos onde fazemos um sistema apenas interno, onde temos certeza que só vão usar aquele browser, e mesmo assim não é recomendavel) nós temos que fazer scripts que rodem em qualquer browser.&lt;br /&gt;&lt;br /&gt;Inicialmente o JavaScript era visto como uma "gambiarra" da web, que estava completamente fora de padrões. Essa visão tem mudado recentemente devido a difusão do AJAX (Asyncronous Javascript And XML), e não foi o JavaScript que mudou, e sim os programadores que comecaram a fazer seu uso de forma correta.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Chega de blablabla&lt;/b&gt;&lt;br /&gt;Se você teve paciência para ler até aqui ótimo (mas nem vem, eu sei que teve gente que pulo os textos anteriores, mas tudo bem XD).&lt;br /&gt;&lt;br /&gt;Vamos comecar entendendo o conceito de funções e variáveis em Javascript. A declaração de variáveis em JavaScript é algo muito simples, para os testes iniciais usaremos o seguinte padrão:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&amp;lt;html&amp;gt;&lt;br /&gt;&amp;lt;head&amp;gt;&lt;br /&gt; &amp;lt;title&amp;gt; JavaScript Dev &amp;lt;/title&amp;gt;&lt;br /&gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&amp;lt;body&amp;gt;&lt;br /&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Como podem ver temos um HTML simples, para escrever JavaScript nós usamos a tag &amp;lt;script type="text/javascript"&amp;gt;&amp;lt;/script&amp;gt;, nossos scripts vão ficar dentro dessas tags. obs: os códigos a seguir devem ficar entre as tags &amp;lt;script&amp;gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var a = 5;&lt;br /&gt;var b = 10;&lt;br /&gt;var c = a + b;&lt;br /&gt;&lt;br /&gt;alert(c);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Isso foi uma simples declaração de variáveis, declaramos a variável &lt;b&gt;a&lt;/b&gt; com o valor 5, depois declaramos a variável &lt;b&gt;b&lt;/b&gt; com o valor 10 e finalmente a variável &lt;b&gt;c&lt;/b&gt; que tem o valor da soma de &lt;b&gt;a&lt;/b&gt; com &lt;b&gt;b&lt;/b&gt;, então usamos a função &lt;b&gt;alert()&lt;/b&gt; que abre uma caixa de texto com um valor (que no nosso caso vai exibir o valor da variável &lt;b&gt;c&lt;/b&gt;).&lt;br /&gt;&lt;br /&gt;Em JavaScript as variáveis não são tipadas, ou seja, a mesma variável pode ter um valor numérico, ou string, ou objeto ou qualquer tipo desejado, isso tem uma perda de desempenho, mas para casos de linguagens isso é mais benefício do que perda.&lt;br /&gt;&lt;br /&gt;Vamos ver agora a declaração de funções:&lt;br /&gt;&lt;code&gt;function testeFuncao() {&lt;br /&gt; alert('a função foi executada');&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;testeFuncao();&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Declaramos a função &lt;b&gt;testeFuncao()&lt;/b&gt; que simplesmente exibe uma caixa com uma mensagem, as funções podem retornar (ou não) um valor, nesse nosso primeiro exemplo ela não retorna nada, ela apenas executa (seria o caso de funções void em linguagens como &lt;b&gt;C&lt;/b&gt; ou &lt;b&gt;Java&lt;/b&gt;). Agora vamos ver uma função que retorna um valor:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;function soma(a, b) {&lt;br /&gt; return a + b;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var n1 = 5;&lt;br /&gt;var n2 = 3;&lt;br /&gt;var valor = soma(n1, n2);&lt;br /&gt;&lt;br /&gt;alert(valor);&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Agora temos algo um pouco mais complicado, como podem ver, dessa vez a função recebe 2 parâmetros, quando declaramos parâmetros para as funções, temos seus nomes, e eles devem ser passados na mesma ordem que foram declarados (ou seja, nosso &lt;b&gt;n1&lt;/b&gt; vai virar &lt;b&gt;b&lt;/b&gt; e &lt;b&gt;n2&lt;/b&gt; vai virar &lt;b&gt;b&lt;/b&gt;), oque a função faz é pegar esses 2 parâmetros e soma-los, retornando esse resultado. Logo após a declaração nós criamos as variaveis &lt;b&gt;n1&lt;/b&gt; e &lt;b&gt;n2&lt;/b&gt;, depois mandamos a variável &lt;b&gt;valor&lt;/b&gt; guardar o resultado da soma das duas (usando a nossa função &lt;b&gt;somar&lt;/b&gt;), e finalmente mandamos exibir esse resultado.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Escopo de variáveis&lt;/b&gt;&lt;br /&gt;Por ultimo vamos entender um pouco sobre escopo de variáveis. O escopo de uma variável serve para saber onde está aquela variável, pois podemos ter varias variáveis com o mesmo nome em escopos diferentes. Vamos entender melhor isso atravéz de um exemplo:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;var minhaVariavel = 10;&lt;br /&gt;&lt;br /&gt;function mostraGlobal() {&lt;br /&gt; alert(minhaVariavel);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function mostraLocal() {&lt;br /&gt; var minhaVariavel = 5;&lt;br /&gt; alert(minhaVariavel);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function mexeGlobal() {&lt;br&gt;&lt;br /&gt; minhaVariavel += 3;&lt;br /&gt; alert(minhaVariavel);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function mexeLocal() {&lt;br&gt;&lt;br /&gt; var minhaVariavel = 2;&lt;br /&gt; minhaVariavel += 5;&lt;br /&gt; alert(minhaVariavel);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;mostraGlobal();&lt;br /&gt;mostraLocal();&lt;br /&gt;mostraGlobal();&lt;br /&gt;mexeGlobal();&lt;br /&gt;mexeLocal();&lt;br /&gt;mexeGlobal();&lt;br /&gt;mexeLocal();&lt;br /&gt;mexeGlobal();&lt;br /&gt;mexeLocal();&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Temos agora várias funções, primeiro declaramos a variável global chamada &lt;b&gt;minhaVariavel&lt;/b&gt;, vemos nas funções a parte interessante, se você chamar uma variável que não foi declarada dentro da função, ele vai buscar essa variável no escopo global (na verdade, o escopo global do javascript é o objeto window, ou seja, chamar uma variavel dessa forma seria a mesma coisa que escrever &lt;b&gt;window.minhaVariavel&lt;/b&gt;, mas você não precisa entender isso agora, nos próximos artigos isso será melhor explicado), e caso não encontre no escopo global ele vai retonar uma valor &lt;b&gt;undefined&lt;/b&gt;. Já se dentro da função nós declaramos &lt;b&gt;var minhaVariavel&lt;/b&gt; ele vai criar uma nova variável com esse nome no escopo da função, com isso ele sempre vai mexer na variável local, e vai deixar a global de lado. Podem ver o seguinte, no script nós executamos primeiro a função que exibe a variável global, depois chamamos a função que mostra a local, como podem ver, na que mostra a variável local nos fazemos uma atribuição à variável, e depois mostramos a global novamente, para provar que ela não foi alterada. Nos outros testes nós mexemos algumas vezes na variável em diferentes escopos, e como podem ver a variável global sempre vai mudando, enquanto a local sempre é uma nova variável.&lt;br /&gt;&lt;br /&gt;Por hoje isso é tudo. Tentei nesse artigo ensinar o básico sobre variáveis e funções, a parte de escopo pode ter ficado um pouco difícil de entender para algumas pessoas, mas não se preocupe, nos futuros artigos iremos entender melhor como funciona o escopo e ficará mais facil.&lt;br /&gt;&lt;br /&gt;Quem já entende de JavaScript pode ter achado isso muito chato, mas futuramente entraremos em assuntos bem mais complexos do JavaScript, então aguardem os futuros artigos.&lt;br /&gt;&lt;br /&gt;Em caso de dúvidas me mandem um e-mail no seguinte endereço: &lt;a href="mailto:wilkerlucio@globo.com"&gt;wilkerlucio@globo.com&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Grato a atenção de quem leu meu artigo, o segundo artigo vai aprofundar o estudo de funções.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/34235652-115800897949430990?l=jsdev.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jsdev.blogspot.com/feeds/115800897949430990/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=34235652&amp;postID=115800897949430990&amp;isPopup=true' title='2 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800897949430990'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/34235652/posts/default/115800897949430990'/><link rel='alternate' type='text/html' href='http://jsdev.blogspot.com/2006/09/conceitos-variveis-e-funes.html' title='Conceitos, Variáveis e Funções'/><author><name>Wilker Lúcio</name><uri>http://www.blogger.com/profile/08197133298620910758</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://4.bp.blogspot.com/_0JOQPTr_DS4/Sb_5vV3JukI/AAAAAAAAAKs/3f8XT2YrKpQ/S220/jipe.jpg'/></author><thr:total>2</thr:total></entry></feed>
