Date post: | 22-Jun-2015 |
Category: |
Technology |
Upload: | leonardo-balter |
View: | 2,215 times |
Download: | 2 times |
WTF Javascript
Leo Balter
Leo Balter@leobalter
Javascript é bom!
Design Patterns vs. Padrões
Padrões
•Patterns
•Standards
•Default
Escala Pentatônica
Patterns são modelos funcionais, mas não precisamos adota-los sempre!
Anti Padrões
fórmulas perfeitas para seu projeto dar errado!
(1 < 2 < 3); // false!
document.all
O Javascript já foi assustador no ano passado!
O retorno maldito!
function(){ return { trololo: “document.all” }}
function(){ return; { trololo: “document.all” }}
function() {return {trololo: “document.all”
}}
Loop desgraçado
var nome = [ “Leo”, “Balter” ];for (i in nome) {console.log(nome[i]);
}
var nome = [ “Leo”, “Balter” ];for (i in nome) {console.log(nome[i]);
}
var nome = [ “Leo”, “Balter” ];for (i in nome) {console.log(nome[i]);
}
var pessoa = function (a, b) { this.nome = a, this.sobrenome = b };
pessoa.prototype.falar = function () { console.log("olá");};
var mim = new pessoa("Leo", "Balter");
for (i in mim) { console.log(mim[i]); // wtf}
var pessoa = function (a, b) { this.nome = a, this.sobrenome = b };
pessoa.prototype.falar = function () { console.log("olá");};
var mim = new pessoa("Leo", "Balter");
for (i in mim) { console.log(mim[i]); // wtf}
var nome = [ “Leo”, “Balter” ];for (i in nome) {if (nome.hasOwnProperty(i)) {console.log(nome[i]); // wtf
}}
Globais e locais
imGlobal = 10;
function changeGlobal() { console.log(imGlobal); // 10 (*) imGlobal = 20;}
changeGlobal();
console.log(imGlobal); // 20
imGlobal = 10;
function changeGlobal() { console.log(imGlobal); // undefined var imGlobal = "What am I?";}
changeGlobal();
imGlobal = 10;
function changeGlobal() { var imGlobal;
console.log(imGlobal); // undefined imGlobal = "What am I?";}
changeGlobal();
Sempre declare suas variáveis no início da função!
imGlobal = 10;
function changeGlobal() { console.log(window.imGlobal); // 10! var imGlobal = "What am I?";}
changeGlobal();
Conheça seu escopo!
Variáveis dentro de blocos de loop, ifs ou switches não criam um escopo interno!
function foo() { var bar = [ 123, 234, 345 ], x = 5; for (var i = 0; i < bar.length; i++) { var x = i; } console.log(i);}foo();
function foo() { var bar = [ 123, 234, 345 ], x = 5; for (var i = 0; i < bar.length; i++) { var x = i; } console.log(i, x); // 3, 3}foo();
function foo() { var bar = [ 123, 234, 345 ], x = 5; for (var i = 0; i < bar.length; i++) { var x = i; } console.log(i, x); // 3, 3}foo();
Valores verdadeiros podem ser falsos!
console.log(!!0); // falseconsole.log(!!10); // trueconsole.log(!!"0"); // true
console.log(0 == ""); // trueconsole.log(!!0 == !!""); // true
console.log(!!0); // falseconsole.log(!!10); // trueconsole.log(!!"0"); // true
console.log(0 == "0"); // trueconsole.log(!!0 == !!"0"); // false
Pare de utilizar == e comece a utilizar === agora!
console.log(90 === "90"); // falseconsole.log(0 !== false); // true
Fuja dos números octais!
parseInt(“042”); // 34
parseInt(“042”, 10); // 42
Cuidado com os tipos
120 + “7”; // “1207”
1 < 2 < 3; // false
1 < 2 < 3;
(1 < 2) < 3;
true < 3;
O eval() é mal!
eval(‘/* js dentro de uma string! */’);
setTimeout(‘rotina(x);’, 500);
setTimeout(function () { rotina(x);}, 500);
Convenções de código
Convenções de código
• JSLint se você for o Douglas Crockford
• JSHint se você não for o Douglas Crockford
• e agora também o CSSLint!
JSLint
• Douglas Crockford
• “JSLint will hurt your feelings”
• Escreva JS como ele escreve ou não use a ferramenta
• for (var x in y) ...
• http://www.jslint.com
JSHint
• Comunidade - fork do JSLint iniciado por Anton Kovalyov
• “does not tyrannize your code”
• Estabeleça as suas convenções!
• Douglas Crockford diz que JSHint é para babacas
• http://jshint.com
function(foo) { var i = -1 var str
for (var i = 0; i < 4; i++) { debugger; str += i; }}()
The code check failed.
Errors:• Line 1 function(foo) {Missing name in function declaration.
• Line 2 var i = -1Missing semicolon.
• Line 3 var strMissing semicolon.
• Line 5 for (var i = 0; i < 4; i++) {'i' is already defined.
• Line 9 }()Function declarations are not invocable. Wrap the whole function invocation in parens.
• Line 9Stopping, unable to continue. (100% scanned).
Outras dicas para melhorar seu JS
Entenda Javascript
• jQuery
• Mootools
• CoffeScript
• Dojo
• Prototype
Use o console!
Use o console!
• Opera Dragonfly
• Chrome Developer Tools
• Firefox’s Firebug (extensão)
• Safari’s Developer Tools
• Internet Explorer Developer Tools
Largue o alert! Use o console.log e debugger!
breakpoint simples!
Não se preocupe com a tecnologia server-side
• Ruby
• Python
• PHP
• .NET
• ColdFusion
• ASP
• C / C++
• Perl
• Erlang
• Lisp
• Cobol
• Pseudo-código
Mas se puder escolher prefira node.js
• Javascript em server side
• é fácil
• é grátis
• é tendência
• se integra facilmente com ferramentas como CSSLint e JSHint
• http://nodejs.org
Passe a ideia adiante!
Estude muito!
• Mozilla Developer Network - MDN - https://developer.mozilla.org/
• Google Code University - http://code.google.com/intl/pt-BR/edu/submissions/html-css-javascript/
• Livros! Ex.: “Padrões Javascript”
Compartilhe seu código e troque experiências!
• Google Code
• Github
• Bitbucket
• jsfiddle.net
• jsbin.com
Não leia o W3Schools!
• Leia o http://w3fools.com
• Pior forma de aprender é a errada!
Não detecte o browser, mas a funcionalidade
Moral da história
você já pode transformar o seu maior vilão no seu melhor amigo!