javascript do jeito certo
TRANSCRIPT
do jeito certoJavascript
Alexandre Gomes
javascripta que te remete o termo?
<form> <input type=button value="Close Window" onClick="javascript:window.close();"> </form>
<script> function open_window(url) { mywin = window.open(url,"win",...); } </script>
<body> <a href = "javascript:open_window('page1.html')"> <img src ="image.gif"> </a> <a href = "javascript:open_window('page2.html')"> <img src ="image.gif"> </a> </body>
function validateForm() { var x = document.forms["myForm"]["fname"].value if (x == null || x == "") { alert("Nome obrigatório!"); return false; } }
para a grande maioria,
javascript = magia negra
Javascript
https://github.com/blog/2047-language-trends-on-github
javascriptAfinal,
é do mal ou do bem?
ECMAScript is an object-oriented programming
language for performing computations and manipulating
computational objects within a host environment.
“
ECMAScript Language Specification 6th edition (June 2015)
ECMAScript as defined here is not intended to be
computationally self-sufficient; indeed, there are no provisions in
this specification for input of external data or output of
computed results.
“
ECMAScript Language Specification 6th edition (June 2015)
Instead, it is expected that the computational environment
(host environment) of an ECMAScript program will
provide not only the objects and other facilities described in this specification but also certain
environment-specific host objects
“
ECMAScript Language Specification 6th edition (June 2015)
ECMAScript was originally designed to be used as a scripting language, but has become widely
used as a general purpose programming language.
“
ECMAScript Language Specification 6th edition (June 2015)
Some of the facilities of ECMAScript are similar to those
used in other programming languages; in particular JavaTM,
Self, and Scheme
“
ECMAScript Language Specification 6th edition (June 2015)
A web browser provides an ECMAScript host environment for client-side computation
including, for instance, objects that represent windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history,
cookies, and input/output.
“
navigator.appName;window.moveTo(100,100);
ECMAScript Language Specification 6th edition (June 2015)
Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image
loading, unloading, error and abort, selection, form submission, and mouse actions.
“<button type="button" onclick="displayDate()"> Display Date</button>
ECMAScript Language Specification 6th edition (June 2015)
The scripting code is reactive to user interaction and
there is no need for a main program.
“<!-- Ate parece, mas nao e o ‘main’ do javascript --><script type="text/javascript">function load() { alert("Page is loaded");}
</script>
<body onload="load()">
ECMAScript Language Specification 6th edition (June 2015)
A web server provides a different host environment for server-side computation including objects
representing requests, clients, and files; and mechanisms to lock and
share data.
“
ECMAScript Language Specification 6th edition (June 2015)
Each Web browser and server that supports ECMAScript supplies its own host environment, completing the ECMAScript
execution environment.
“
ECMAScript Language Specification 6th edition (June 2015)
ECMAScript is an object-oriented programming language
(...)
“Operadores
Tipos
Comentários
Estruturas
Boolean, Number, String, Array, RegExp
+ - * / >> << >>> < > <= >= | & *= ^ ++
// /* */
do while for if else try catch switch
ECMAScript Language Specification 6th edition (June 2015)
Tipos
Boolean
Number
String
Array
Object
Function
RegExp
Date
(construtores)
var x;alert(x);
Tiposundefined
ECMAScript Language Specification 6th edition (June 2015)
var x = null;alert(x);
Tiposnull
ECMAScript Language Specification 6th edition (June 2015)
var x = true;if(x) { alert('Verdadeiro');}
Obs: 0 e null equivalem a false
TiposBoolean
ECMAScript Language Specification 6th edition (June 2015)
var x = 10;var y = 15;alert(x+y);
var x = 10.1;var y = 15.2;alert(x+y);
TiposNumber
ECMAScript Language Specification 6th edition (June 2015)
var x = “Alexandre”;alert(x);
TiposString
ECMAScript Language Specification 6th edition (June 2015)
var x = function() { alert("Alexandre"); };x();
TiposFunction
ECMAScript Language Specification 6th edition (June 2015)
> var x = true;> x.constructor;Boolean()
> var x = "Alexandre";> x.constructor;String()
> var x = 3467;> x.constructor;Number()
> var x = function() { alert("Alexandre"); };> x.constructor;Function()
var x = new Number(10);var y = new Number(15);alert(x+y);
var x = new Boolean(true);if(x) { alert('Verdadeiro'); }
var x = new String(“Alexandre”);alert(x);
Operadores
delete
void
typeof
++
--
+
-
~
!
*
/
%
>>
<<
>>>
<
>
<=
>=
instanceof
in
==
!=
===
!==
&
^
|
&&
||
<<=>>=
? :
=
*=
/=
%=
+=
-=
>>>=
&=
ˆ=
|=
Operadores
ECMAScript Language Specification 5th edition (December 2009)
var a = 1 undefined a 1 delete a true a ReferenceError: a is not defined
delete
Operadores
ECMAScript Language Specification 5th edition (December 2009)
typeof 1 "number" typeof true "boolean" typeof "Alexandre" "string" typeof function() { alert('Oi') } "function" typeof null "object"
typeof
Operadores
ECMAScript Language Specification 5th edition (December 2009)
var a = 1 undefined a++ 1 a 2 ++a 3
++ e --
Operadores
ECMAScript Language Specification 5th edition (December 2009)
var a = "alexandre" undefined a instanceof String false var a = new String("alexandre") undefined a instanceof String true a instanceof Object true
instanceof
http://mzl.la/PqqTMy
Operadores
ECMAScript Language Specification 5th edition (December 2009)
3 == "3" true 3 === "3" false
2 != "2" false 2 !== "2" true
==, !=, ===, !==
Estruturas
if/else
do/while
while
for
for/in
continue
break
return
with
switch
throw
try/catch
debugger
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
var a = true
if (a) { alert('Verdadeiro') } else { alert('Falso') }
if/else
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
var i = 1 do { alert(i); i++; } while (i < 5)
do/while
(...)
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
for ( var i = 1; i < 5; i++) { alert(i); }
for
(...)
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
var array = [1,3,5,7,9]
for (var i in array) { alert(array[i]) }
for/in
(...)
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
> var obj = { a: 1, b: 3, c: 5 }
> obj.a 1
> for(p in obj) { alert(p + ": " + obj[p]) }
> for each (v in obj) { alert(v) // v aqui igual ao obj[p] acima }
for/each/in
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
var obj = { a: 1, b: 3, c: 5 }
alert(obj.a); // 1 alert(obj.b); // 3 alert(obj.c); // 5
with(obj) { alert(a); // 1 alert(b); // 3 alert(c); // 5 }
with
Estruturas
ECMAScript Language Specification 5th edition (December 2009)
var a = "alexandre";
switch (a) {
case "sebastiao": alert("Tião?"); break;
case "raimunda": alert("Raimundinha?"); break;
case "alexandre": alert("Alê!"); break; }
switch/case
ECMAScript is object-based: basic language and host facilities are provided by
objects, and an ECMAScript program is a cluster of communicating objects.
“
ECMAScript Language Specification 5th edition (December 2009)
Numa aplicação Javascript, coexistirão
3 grupos de objetos
especificação ECMAScript
objetos definidos pela
Boolean
Number
String
Array...
desenvolvedorobjetos definidos pelo
alexandre
mensagem
...
web browserobjetos definidos pelo
window
document
...
XMLHttpRequest
An ECMAScript object is a collection of properties
each with zero or more attributes that determine how each property can be used
“
ECMAScript Language Specification 5th edition (December 2009)
alexandre
nome: “Alexandre”sobrenome: “Gomes”idade: 34
modificável: false
> var ale = new Object()
> ale.nome = "Alexandre Gomes" "Alexandre Gomes" > ale.nascimento = new Date(1977,8,8) Thu Sep 08 1977 00:00:00 GMT-0300 (BRT)
> ale.nome "Alexandre Gomes" > ale.nascimento Thu Sep 08 1977 00:00:00 GMT-0300 (BRT)
> ale[‘nome’] "Alexandre Gomes" > ale[‘nascimento’] Thu Sep 08 1977 00:00:00 GMT-0300 (BRT)
Properties are containers (slots) that hold other objects, primitive values, or functions. “
ECMAScript Language Specification 5th edition (December 2009)
alexandre
nome: “Alexandre”
idade: function() { ... }
nascimento: new Date(1977,8,8,0,0,0,0)
ECMAScript defines a collection of built-in objects“
Function, Array, String, Boolean, Number, Math, Date, RegExp, JSON
Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError e URIError
ECMAScript Language Specification 5th edition (December 2009)
> var x = "Alexandre";> x.length9
> x.charAt(5);"n"
> x + " Gomes""Alexandre Gomes"
> x.replace("dre", "dro");"Alexandro"
> x.big()"<big>Alexandre</big>"
> x.link("http://alegom.es")"<a href="http://alegom.es">Alexandre</a>"
String
>>> var x = true;>>> if(x) { alert('yes'); } else { alert('no') } // yes
>>> !xfalse
>>> x & false0>>> x && falsefalse>>> x | false1>>> x || falsetrue
>>> var x = false;>>> if(x) { alert('yes'); } else { alert('no') } // no
Boolean
>>> var x = 10>>> var y = 15;>>> z = x + y25
>>> z.toFixed(2);"25.00"
>>> z.toExponential(2);"2.50e+1"
>>> 2.toExponential(2);SyntaxError: identifier starts immediately after numeric literal
Number
>>> Math.PI3.141592653589793
>>> Math.sqrt(81);9
>>> Math.tan(45);1.6197751905438615
>>> Math.pow(3,2);9
>>> Math.random();0.8528815588353642>>> Math.random();0.955940929887219
Math
>>> var x = new Date();>>> x.toString();"Sun Apr 03 2011 12:20:42 GMT-0300 (BRT)"
>>> x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();"12:20:42"
>>> x.getDate() + "/" + x.getMonth() + "/" + x.getFullYear();"3/3/2011"
>>> var x = new Date("5/18/2006");>>> x.toString();"Thu May 18 2006 00:00:00 GMT-0300 (BRT)"
>>> var x = new Date("2006-5-18");>>> x.toString();"Invalid Date"
>>> var x = Date(2006,5,18,10,11,12,13);>>> x.toString();"Sun Jun 18 2006 10:11:12 GMT-0300 (BRT)"
Date
>>> var x = new Date();>>> x.toString();"Sun Apr 03 2011 12:20:42 GMT-0300 (BRT)"
>>> x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();"12:20:42"
>>> x.getDate() + "/" + x.getMonth() + "/" + x.getFullYear();"3/3/2011"
>>> var x = new Date("5/18/2006");>>> x.toString();"Thu May 18 2006 00:00:00 GMT-0300 (BRT)"
>>> var x = new Date("2006-5-18");>>> x.toString();"Invalid Date"
>>> var x = Date(2006,5,18,10,11,12,13);>>> x.toString();"Sun Jun 18 2006 10:11:12 GMT-0300 (BRT)"
Date
>>> var texto = "O gato roeu a roupa do rei de roma";>>> var regex = new RegExp("gato", “”);
>>> texto.match(regex);["gato"]>>> regex.exec(texto);["gato"]
>>> texto.match(/gato/);["gato"]
>>> texto.match(/O gato/);["O gato"]>>> texto.match(/o gato/);null>>> texto.match(/o gato/i);["O gato"]
>>> texto.match(/o gato.*/i);["O gato roeu a roupa do rei de roma"]
Regex
>>> var obj = { "nome": "Alexandre", "idade" : "33" }>>> obj.constructor;Object()>>> obj.nome"Alexandre">>> obj.idade"33"
>>> var msg = JSON.stringify(obj);>>> msg.constructor;String()>>> msg"{"nome":"Alexandre","idade":"33"}"
>>> var msg = '{ "nome": "Alexandre", "idade" : "33" }'"{ "nome": "Alexandre", "idade" : "33" }">>> msg.constructor;String()>>> msg.nome;undefined
>>> obj = JSON.parse(msg);Object { nome="Alexandre", idade="33"}>>> obj.constructor;Object()>>> obj.nome;"Alexandre"
JSON
var x = new Array();>>> []
x[0] = "laranja">>> ["laranja"]
x[2] = "maçã">>> ["laranja", undefined, "maçã"]
x.length>>> 3
x.sort();>>> ["laranja", "maçã", undefined]
x.reverse();>>> [undefined, "maçã", "laranja"]
x = ["pera", "uva", new Date()]x.toString();>>> "pera,uva,Sun Apr 03 2011 11:53:18 GMT-0300 (BRT)"
Array
A web browser provides an ECMAScript host environment
(...)
“
> document.body 1.<body id="docs" class="section-docs en ltr yui-skin-sam
PageDW-enDOMdocument js" role="document">…</body>
> document.domain "developer.mozilla.org"
> document.links [ <a href="#content-main">Skip to the main content</a>,
<a href="#q">Skip to the site search</a>, <a href="/">…</a>, <a href="/index.php?" class="user-login">Log in</a>, <a href="/docs">Doc Center</a>, …
Gecko Webkit{ {
e agora, prendam a respiração...
REVISÃO
An ECMAScript object is a collection of properties
each with zero or more attributes that determine how each property can be used
“
ECMAScript Language Specification 5th edition (December 2009)
alexandre
nome: “Alexandre Gomes”idade: 34
modificável: false
andar: function() { ... }
alexandre
nome: String()idade: Number()
modificável: Boolean()
andar: Function()
alexandre
nome: Object()idade: Object()
modificável: Object()
andar: Object()
alexandre
nomeidade
modificável
andar
String()
Number()
Boolean()
Function()
ECMAScript does not use classes such as those in C++,
Smalltalk, or Java.
“
ECMAScript Language Specification 5th edition (December 2009)
apesar de ser OO,
“Classful” “Classless”reuso por herança
de classesreuso por clonagem
de objetos
Pessoa
nomesexo
Funcionário
salário
joao
nome: “João”idade: 28
maria
nome: “Maria”idade: 20
<<herda>> <<clona>>
“Classful” “Classless”modelagem
top-downmodelagem bottom-up
primeiro a taxonomia e seus relacionamentos...
primeiro o comportamento...
“Classful” “Classless”
objetos criados a partir de classes
objetos criados a partir de clonagem...
...ou por ‘geração expontânea’
hoje = new Date() hoje = new Date()
var x = { one: 1, two: 2}
“Classful” “Classless”
objetos carregam a estrutura e o
comportamento de sua classe
objetos carregam as características de seu
protótipo
Programação baseada em
protótipos
protótipo clone
Programação baseada em
protótipos>>> var conta = { saldo: 1000.00 };>>> conta.saldo1000>>> conta.limiteundefined
>>> var conta_especial = { limite: 500.00 }>>> conta_especial.limite500>>> conta_especial.saldoundefined
>>> conta_especial.__proto__ = conta // referência explícitaObject { saldo=1000}>>> conta_especial.saldo1000
Herança baseada em
protótipos> var conta = function(saldo) { this.saldo = saldo; this.ver_saldo = function() { alert('saldo = ' + this.saldo) } }
> c1 = new conta(1000) > c1.ver_saldo()
> var conta_especial = function(saldo, limite) { this.inheritFrom = conta; this.inheritFrom(); this.saldo = saldo; this.limite = limite; }
> c2 = new conta_especial(2000,3000) > c2.ver_saldo()
objects may be created in various ways including
via a literal notation
“
ECMAScript Language Specification 5th edition (December 2009)
hoje = new Date()
var conta = { saldo: 1000.00 }
or via constructors
Each constructor is a function
“
ECMAScript Language Specification 5th edition (December 2009)
hoje = new Date()
function Date() {...}
function é também um objeto
var Date = function() {...}
mas
Date()
hoje = new Date()
construtor
Date()function
objeto
propriedades
Each constructor is a function that has a property
named “prototype” that is used to implement
prototype-based inheritance and shared properties.
“
ECMAScript Language Specification 5th edition (December 2009)
Each constructor is a function that has a property named “prototype”(...)“
ECMAScript Language Specification 5th edition (December 2009)
Date()
prototype
Protótipo do Date()
<<construtor>>
Every object created by a constructor“
ECMAScript Language Specification 5th edition (December 2009)
Date()
prototype
hoje = new Date() hojeprototype
Protótipo do Date()
<<construtor>>
has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property.
Furthermore, a prototype may have a non-null implicit reference to its prototype,
and so on; this is called the prototype chain.
“
ECMAScript Language Specification 5th edition (December 2009)
Date()
Protótipo do Date()
<<construtor>> Protótipo do protótipo do
Date()
Protótipo do protótipo do protótipo do
Date()
When a reference is made to a property in an object, that reference is to the
property of that name in the first object in the prototype chain that contains a
property of that name.
“
ECMAScript Language Specification 5th edition (December 2009)
obj
p2: “dois”
p3: “tres”
p4: “quatro”
p1: “um”
obj.p1obj.p2obj.p3obj.p4
> var Pessoa = function(nome, idade) { this.nome = nome; this.idade = idade; }
> var alexandre = new Pessoa('Ale', 33);> alexandre.nome"Ale"> alexandre.idade33
> var sebastiana = new Pessoa('Sebastiana', 88);> sebastiana.nome"Sebastiana"> sebastiana.idade88
construtor
objeto 1
objeto 2
Protótipo do Pessoa()
Pessoa()<<construtor>>
nomeidade
> alexandre.sexo
undefined ?> sebastiana.sexo
undefined ?alexandre sebastiana
nome = ‘Ale’
idade = 33nome = ‘Seb...’
idade = 88
> alexandre.nome
“Ale” ?> sebastiana.idade
88 ?
Protótipo
Pessoa()<<construtor>>
nomeidade
> alexandre.sexo
“M”
> sebastiana.sexo
“M”
alexandre sebastiana
nome = ‘Ale’
idade = 33nome = ‘Seb...’
idade = 88
> Pessoa.prototype.sexo = “M”
> sebastiana.sexo = “F”
> sebastiana.sexo
“F”
sexo = ‘M’
Object Prototipo de Object
pO = 1
Object.prototype.pO = 1
A
a = 2
Prototipo de A
pA = 3
var A = function() { this.a = 2; }A.prototype.pA = 3
Object Prototipo de Object
pO = 1
new A()
A
a = 2
Prototipo de A
pA = 3
var B = function() { this.b = 4; }
Object Prototipo de Object
pO = 1
B
b = 4
Prototipo de B
pB = 5
B.prototype = new AB.prototype.pB = 5
a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
x = new B()
new A() X
a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
new A() X
x.pB?a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
new A() X
x.b?a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
new A() X
x.pA?a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
new A() X
x.a?a = 2
A
a = 2
Prototipo de A
pA = 3
Object Prototipo de Object
pO = 1
B
b = 4pB = 5
new A() X
x.pO?a = 2
@see
https://developer.mozilla.org/en/JavaScript/Reference
http://www.w3schools.com/js/default.asp
https://developer.mozilla.org/en/Gecko_DOM_Reference
http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/WebKitDOMRef/index.html
o que tem sido feito com
javascript?
http://jquery.com/
• Ajax • Animation and Effects • Browser Tweaks • Data • DOM • Drag-and-Drop • Events • Forms • Integration • JavaScript • jQuery Extensions
• Layout • Media • Menus • Metaplugin • Navigation • Tables • User Interface • Utilities • Widgets • Windows and Overlays
http://plugins.jquery.com/
http://raphaeljs.com/
Node's goal is to provide an easy way to build scalable
network programs.
http://nodejs.org/
http://documentcloud.github.com/backbone/
Backbone supplies structure to JavaScript-heavy applications by providing models with key-value
binding and custom events, collections with a rich API of enumerable functions, views with declarative
event handling, and connects it all to your existing application over a RESTful JSON interface.
CoffeeScript is a little language that compiles into JavaScript. (...)
CoffeeScript is an attempt to expose the good parts of JavaScript in a
simple way.
http://jashkenas.github.com/coffee-script/
if (opposite) { number = -42;}
number = -42 if opposite
square = function(x) { return x * x;};
square = (x) -> x * x
cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results;})();
cubes = (math.cube num for num in list)
http://en.wikipedia.org/wiki/JavaScript_framework
P&Raprender.unb.br