elcsat Posted September 29, 2009 at 11:11 AM Report Share #289151 Posted September 29, 2009 at 11:11 AM ola, gostava de tirar algumas duvidas javascript 1- para que serve isto, vantagens e como se usa? (function(){ // codigo.... }) 2- para que serve estas duas expressoes regularares? quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, isSimple = /^.[^:#\[\.,]*$/; 3- para que server usar o ponto no nome das funçoes? por exemplo funcao.teste obrigado. 😄 Link to comment Share on other sites More sharing options...
IceBrain Posted September 29, 2009 at 12:12 PM Report Share #289155 Posted September 29, 2009 at 12:12 PM Bom, se me enganar corrijam-me: 1. É uma função anónima, ou seja, uma função como as outras mas que não tem nome. São úteis principalmente em situações em que a função é apenas temporária, e só vai ser utilizada numa altura específica do programa. Exemplo: Imagina que tens um array de inteiros: var myarray = [4, 5, 19, 1, 3]; Se os quiseres ordenar poderias ser tentado a usar o método sort(): myarray.sort(); O problema, é que esse método, se for chamado sem parâmetros, ordena os valores como sendo strings, o que pode causar problemas inesperados. Neste caso, a myarray ficaria: [1, 19, 3, 4, 5] O que não é, obviamente, o resultado certo. Para poder ordenar quaisquer tipos de valor, o método sort() permite receber uma função que recebe dois valores (A e B) e os compara, retornando um número positivo se A > B, negativo se B > A, e zero se A = B. Visto que a função vai ser usada apenas neste sort e não vai ser precisa no resto do programa, em vez de declarares a função com um nome (que possivelmente até poderia colidir com outro já existente), passas uma função anónima: myarray.sort( function(a, b) { return b - a; } ); 2. Não faço ideia, sorry 😞 3. Bem, em Javascript as funções não são apenas funções, são na realidade objectos do tipo Function. Assim sendo, podemos associar a esse objecto propriedades, ou mesmo funções, usando as funções anónimas. Exemplo: function minhafuncao() { return 3; } Isto na realidade criou um objecto do tipo Function, chamado minhafuncao. Assim, podemos adicionar-lhe propriedades, como valores normais: minhafuncao.teste = 3; Ou mesmo funções: minhafuncao.teste2 = function() { return "ola"; } //E podemos chamar normalmente, como qualquer método alert( minhafuncao.teste2() ); ❝The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying.❞- John Carmack on software patents A list of command line apps Link to comment Share on other sites More sharing options...
elcsat Posted September 29, 2009 at 10:32 PM Author Report Share #289265 Posted September 29, 2009 at 10:32 PM obrigado amigo IceBrain, pela ajuda. entendi prefeitamente a tua explicaçao. desculpa fazer outra questao, mas relativamente a pergunta 1. como é que eu vou evocar a funçao anonima caso tenha o seguinte codigo, e as que tao dentro dela. (function(){ var a, b="1"; function teste1(){ alert("teste1"); } teste2 = function(){ alert("teste2"); } // mais codigo aqui ................. }) foi daqui que apareceu a minha duvida ?. desde ja muito obrigado pela ajuda. 🙂 :) 👍 Link to comment Share on other sites More sharing options...
IceBrain Posted September 29, 2009 at 10:40 PM Report Share #289267 Posted September 29, 2009 at 10:40 PM Normalmente as funções anónimas são usadas quando é suposto passá-la como parâmetro para outra função... Se a vais evocar, o melhor é mesmo dar-lhe um nome 🙂 Podes evocar uma função anónima se a guardares numa variável, como essa "teste2" que tens aí: var teste2 = function(){ alert("teste2"); } //Depois chamas normalmente: teste2(); Mas isto é equivalente a dar-lhe um nome normalmente... ❝The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying.❞- John Carmack on software patents A list of command line apps Link to comment Share on other sites More sharing options...
elcsat Posted September 29, 2009 at 10:51 PM Author Report Share #289270 Posted September 29, 2009 at 10:51 PM eu isso entendo. mas e que estou a estudar um codigo e nao entendo o motivo de eles o terem escrito assim, como eu escrevi no exemplo. ando as cabeçadas um pouco ao codigo e eu procuro no google function javascript, e so aparece exemplos basicos...nada de funçao anonimas Link to comment Share on other sites More sharing options...
IceBrain Posted September 29, 2009 at 11:57 PM Report Share #289274 Posted September 29, 2009 at 11:57 PM Epá, se postares um excerto do código que contenha o contexto em que essa função é declarada, pode ser que alguém perceba... ❝The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying.❞- John Carmack on software patents A list of command line apps Link to comment Share on other sites More sharing options...
softklin Posted September 30, 2009 at 08:06 AM Report Share #289284 Posted September 30, 2009 at 08:06 AM Estou a dar um tiro completamente no escuro, mas parece-me que aquela primeira expressão regular serve para ver se se trata de uma tag de HTML/XML... A segunda não faço a mínima ideia. :bored: Mas coloca o código em questão, vai ajudar a interpretar os problemas. 🙂 Nick antigo: softclean | Tens um projeto? | Wiki P@P Ajuda a comunidade! Se encontrares algo de errado, usa a opção "Denunciar" por baixo de cada post. Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 10:10 AM Author Report Share #289290 Posted September 30, 2009 at 10:10 AM o codigo começa assim (function(){ var // Will speed up references to window, and allows munging its name. window = this, // Will speed up references to undefined, and allows munging its name. undefined, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, jQuery = window.jQuery = window.$ = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { // Make sure that a selection was provided selector = selector || document; // Handle $(DOMElement) if ( selector.nodeType ) { this[0] = selector; this.length = 1; this.context = selector; return this; } ...................................... ando a estudar o codigo da biblioteca jquery, para melhorar os meus conhecimentos em javascript, e tenho varias duvidas acerca do respectivo codigo. 🙂 Link to comment Share on other sites More sharing options...
IceBrain Posted September 30, 2009 at 02:34 PM Report Share #289330 Posted September 30, 2009 at 02:34 PM Tens a certeza que antes do que meteste aí não há uma chamada a uma função qualquer, e que essa função anónima é passada como argumento? Se não, não vejo a utilidade disso... ❝The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying.❞- John Carmack on software patents A list of command line apps Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 03:23 PM Author Report Share #289338 Posted September 30, 2009 at 03:23 PM começa assim o codigo Link to comment Share on other sites More sharing options...
softklin Posted September 30, 2009 at 04:04 PM Report Share #289346 Posted September 30, 2009 at 04:04 PM É realmente assim que começa o código. O que está antes é os créditos, licença, ... sob forma de um comentário. Aparentemente é algo assim: (function() { ... })(); Para ver isso, basta ir ao source do jquery, uncompressed. Se alguém quiser explicar, também estou disposto a aprender, não faço a mínima do que isso significa. Nick antigo: softclean | Tens um projeto? | Wiki P@P Ajuda a comunidade! Se encontrares algo de errado, usa a opção "Denunciar" por baixo de cada post. Link to comment Share on other sites More sharing options...
IceBrain Posted September 30, 2009 at 04:42 PM Report Share #289350 Posted September 30, 2009 at 04:42 PM Encontrei um link (PDF) que explica o uso desse tipo de sintaxe: http://ajaxian.com/downloads/books/javascriptninja/JavaScriptNinja_ch3_Article2.pdf Sou capaz de traduzir e fazer um artigo da Wiki a partir disso. ❝The idea that I can be presented with a problem, set out to logically solve it with the tools at hand, and wind up with a program that could not be legally used because someone else followed the same logical steps some years ago and filed for a patent on it is horrifying.❞- John Carmack on software patents A list of command line apps Link to comment Share on other sites More sharing options...
yoda Posted September 30, 2009 at 04:44 PM Report Share #289352 Posted September 30, 2009 at 04:44 PM começa assim o codigo Mas tu queres entender o core do JQuery? Boa sorte, tens muitos meses pela frente 🙂 before you post, what have you tried? - http://filipematias.info sense, purpose, direction Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 06:36 PM Author Report Share #289375 Posted September 30, 2009 at 06:36 PM yoda nem por isso se alguem souber ajudar em algumas partes:D no que nao entendo..loll Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 06:38 PM Author Report Share #289376 Posted September 30, 2009 at 06:38 PM obrigado amigo IceBrain Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 08:19 PM Author Report Share #289398 Posted September 30, 2009 at 08:19 PM eu nao consegui meter este exemplo a funcionar var div = document.getElementsByTagName("div"); alert(div.length) for ( var i = 0; i < div.length; i++ )(function(i){ div[i].addEventListener("click", function(){ alert( "div #" + i + " was clicked." );}, false); })(i); o alert dame sempre 0, e eu tenho 3 divs na pagina que tou a testar gostava de tirar outra duvida pode ser burrice mas nao sei o motivo de usar os dois : neste codigo (function(v) { Object.extend(v, { href: v._getAttr, src: v._getAttr, type: v._getAttr, action: v._getAttrNode, disabled: v._flag, checked: v._flag, readonly: v._flag, multiple: v._flag, onload: v._getEv, onunload: v._getEv, onclick: v._getEv // ... }); })(Element._attributeTranslations.read.values); obrigado Link to comment Share on other sites More sharing options...
softklin Posted September 30, 2009 at 08:24 PM Report Share #289399 Posted September 30, 2009 at 08:24 PM Colocaste esse código antes da declaração HTML? Se não me engano, ele corre o javascript de imediato, mesmo antes da página estar renderizada. Experimenta colocar no fim da página, dentro das tags <script></script>. Quanto à dúvida, esses dois pontos é para criares "arrays" com nomes, ou sejas pares chave-valor. Em vez de acederes com i[0], acedes por exemplo com i[nome_da_chave] em que { chave : valor }. Tal como nos arrays de PHP. Nick antigo: softclean | Tens um projeto? | Wiki P@P Ajuda a comunidade! Se encontrares algo de errado, usa a opção "Denunciar" por baixo de cada post. Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 08:52 PM Author Report Share #289404 Posted September 30, 2009 at 08:52 PM em relaçao a isso entendi, vou tentar meter o javascript no fim da pagina ver se funciona, e digo ja algo Link to comment Share on other sites More sharing options...
elcsat Posted September 30, 2009 at 08:54 PM Author Report Share #289405 Posted September 30, 2009 at 08:54 PM funciona, ao colocar o javascript no fim da pagina, obrigado. Link to comment Share on other sites More sharing options...
elcsat Posted October 1, 2009 at 07:15 AM Author Report Share #289463 Posted October 1, 2009 at 07:15 AM amigo softclean, como é que evoco uma funçao deste tipo funcao : function(aa){ // codigo ................ } eu tentei fazer teste : 'qualquer coiser'; alert(teste); isto nao funciona so funciona o alert se fizer assim teste=function(a){ var e=a; } function teste1(a){ a1 : teste; alert(a1); }// isto vai imprmir o codigo todo da funçao teste como é que acedia a funcao plo a1, se é possivel. obrigado 🙂 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now