2. Sobre mim
Sérgio Souza Costa
Professor - UFMA
Doutor em Computação Aplicada (INPE)
prof.sergio.costa@gmail.com
https://sites.google.com/site/profsergiocosta/home
https://twitter.com/profsergiocosta
http://gplus.to/sergiosouzacosta
http://www.slideshare.net/skosta/presentations?order=popular
7. "Combining a functional style with prototypal inheritance JavaScript
is arguably the most widely deployed language of either type.
Considering that virtually every computer user has an interpreter
capable of running it, JavaScript serves to be one of the best
languages to learn."
John Resig
"Considered a “toy” language by serious web developers for
most of its lifetime, Java-Script has regained its prestige in
the past few years as a result of the renewed interest in Rich
Internet Applications and Ajax technologies".
John Resig - jQuery in Action
8. O que preciso saber ?
1. Saber programar
2. Conhecer a linguagem
3. Conhecer suas APIs
9. O que preciso saber ?
1. Saber programar
2. Conhecer a linguagem
3. Conhecer suas APIs
16. JavaScript
● Inicialmente com o nome de Cmm (C menos menos) e depois
ScriptEase.
● Netscape usa o projeto em seu Browser, nomeando como LiveScript
e depois JavaScript.
● Não é derivada do Java, o nome pode ter sido usado como estratégia
de marketing.
● Microsoft incorpora no teu browser com outro nome - JScript.
43. Exemplo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" >
var a = 40
var b = a
b = 30
var p1 = {x:10, y: 20};
var p2 = p1;
p2.x = 50;
p2.y = 80;
console.log (p1, p2, a, b)
</script>
<title></title>
</head>
<body>
</body>
</html>
44. <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" >
var a = 40
var b = a
b = 30
var p1 = {x:10, y: 20};
var p2 = p1;
p2.x = 50;
p2.y = 80;
console.log (p1, p2, a, b)
</script>
<title></title>
</head>
<body>
</body>
</html>
Exemplo
Tipos primitivos
é sempre
atribuído como
cópia.
59. function f () {
for (i in arguments ) {
console.log (i)
}
}
f (1,2)
Funções – Número de argumentos
indefinido
60. Sobrecarga é um tipo de polimorfismo muito útil e
existente em diversas linguagens, mas não existe
nativamente em JavaScript, mas pode ser simulada:
● A partir do número de argumentos passados, dos valores dos
argumentos passados.
Sobrecarga de funções
61. function f (arg) {
if (arg)
console.log (arg)
else
console.log (“ola mundo“)
}
f("oi")
f()
function f (arg) {
if (arguments.length != 0)
console.log (arg)
else
console.log ("ola mundo")
}
f("oi")
f()
Exemplos
63. ●Array
var a = [1,2,3]
●Object
var o = {nome: “joao“, idade:25}
Tipos referência
64. var a = [1,2,3,4]
for (v in a)
{ console.lo
g (v)
}
Array
65. var o = {chave1 : valor1, chave2 : valor2 }
Valores podem ser de qualquer
dos valores existentes em
JavaScript: numéricos, string,
funções, arrays ou objetos
Object
66. var person = new Object();
person.name = “Nicholas”;
person.age = 29;
person.job = “Software Engineer”;
person.sayName = function(){
Console.log(this.name);
};
person.sayName()
Object - Simulando POO
67. var person = new Object();
person.name = “Nicholas”;
person.age = 29;
person.job = “Software Engineer”;
person.sayName = function(){
Console.log(this.name);
};
person.sayName()
Object - Simulando POO
Sempre que criar
um novo „person“,
terei que escrever a
função sayName ?
68. var person = new Object();
person.name = “Nicholas”;
person.age = 29;
person.job = “Software Engineer”;
person.sayName = function(){
Console.log(this.name);
};
person.sayName()
Object - Simulando POO
Sempre que criar
um novo „person“,
terei que escrever a
função sayName ?Criem uma função
para fazer isso
69. function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson(“Nicholas”, 29, “Software
Engineer”);
var person2 = createPerson(“Greg”, 27, “Doctor”);
Object - Simulando POO
70. function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson(“Nicholas”, 29, “Software
Engineer”);
var person2 = createPerson(“Greg”, 27, “Doctor”);
Object - Simulando POO
Linguagens
orientadas a
objetos tem uma
solução melhor:
construtoras.
71. function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person(“Nicholas”, 29, “Software
Engineer”);
var person2 = new Person(“Greg”, 27, “Doctor”);
Object - Simulando POO
72. function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person(“Nicholas”, 29, “Software
Engineer”);
var person2 = new Person(“Greg”, 27, “Doctor”);
Object - Simulando POO
Um problema:
sayName é
replicada em todos
os objetos
73. function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person("Nicholas", 29,"Software
Engineer");
var person2 = new Person("Greg", 27, "Doctor");
Console.log (person1.sayName == person2.sayName )
Object - Prototype
74. function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){
alert(this.name);
};
var person1 = new Person("Nicholas", 29,"Software
Engineer");
var person2 = new Person("Greg", 27, "Doctor");
Console.log (person1.sayName == person2.sayName )
Object - Prototype
Prototype permite
extender as
funcionalidades de
um objeto, ex:
plugins do Jquery
76. Objetos como String e Array, utilizam
prototypes para definir seus “métodos”.
alert(typeof Array.prototype.sort);
alert(typeof String.prototype.substring);
Object - Prototype
77. String.prototype.iniciaCom =
function (text) {
return this.indexOf(text) == 0;
};
var msg = "Hello world!";
console.log(msg.iniciaCom("Hello")
);
Objetos como String e Array, utilizam
prototypes para definir seus “métodos”.
Object - Prototype
78. function Pessoa (name) { this._name = name; }
Pessoa.prototype = {
constructor: Pessoa,
getName : function(){ return (this._name); },
setName : function(name){this._name = name; }
}
var p = new Pessoa ("sergio")
console.log (p.getName())
p.setName ("joao")
console.log (p.getName())
Getters e Setters
79. function Pessoa (name) { this._name = name; }
Pessoa.prototype = {
constructor: Pessoa,
getName : function(){ return (this._name); },
setName : function(name){this._name = name; }
}
var p = new Pessoa ("sergio")
console.log (p.getName())
p.setName ("joao")
console.log (p.getName())
Getters e Setters
Compo possso
usar “sobrecarga”
aqui ?
80. function Pessoa (name) { this._name = name; }
Pessoa.prototype = {
constructor: Pessoa,
getName : function(){ return (this._name); },
setName : function(name){this._name = name; }
name : function () {
if (arguments[0] &&
typeof (arguments[0]) == "string")
return this.setName (arguments[0])
else
return this.getName ()
}
}
var p = new Pessoa ("sergio")
console.log (p.name())
p.name ("joao")
console.log (p.name())
Getters e Setters
81. function Person(name ){
this._name = name;
}
Person.prototype = {
constructor: Person,
get name () {
return this._name;
},
set name (name) {
this._name = name
}
}
a = new Person ("jose")
console.log (a.name);
a.name = "joao"
console.log (a.name);
Getters e Setters
A partir do
JavaScript 1.5
(2000), o java
script permitiu
escrever getter e
setters
82. Exemplo em jQuery
O método $.fn.html usado como setter
$('h1').html('olá mundo');
O método html usado como getter
$('h1').html();
Getters e Setters
84. JSON
JSON é um objeto JavaScript no formato de String
eval ('( {"skillz": {
"web":[
{"name": "html",
"years": "5"
},
{"name": "css",
"years": "3"
}],
"database":[
{"name": "sql",
"years": "7"
}]
}} )')
85. JSON
JSON é um objeto JavaScript no formato de String
eval ('( {"skillz": {
"web":[
{"name": "html",
"years": "5"
},
{"name": "css",
"years": "3"
}],
"database":[
{"name": "sql",
"years": "7"
}]
}} )')
Problem at line 13
character 19: eval is evil.
http://www.jslint.com/
87. Json
Criando e parseando JSON
p = new Object ({
"nome" : "sergio",
"idade" : 30
})
console.log (JSON.stringify (p))
console.log (JSON.parse (JSON.stringify (p)))
http://www.json.org/json2.js.
Browser mais antigos não
inclue esse objeto JSON
88. JSON - Parse
Tratando erro
var jsonString = "{nao eh um json}”"
try {
var jsonObj = JSON.parse(jsonString);
} catch(e) {
console.log("json invalido:", e)
89. JSON - Parse
var jsontext = '{"nome":"sergio", "nascimento":"05 Janeiro
1981"}';
var pessoa = JSON.parse(jsontext);
var pessoa = JSON.parse(jsontext, function (key, value) {
var bDate;
if (key == "nascimento") {
bDate = new Date(value);
return bDate;
}
return value;
});
90. JSON - Stringfy
Formatando a saída
console.log (JSON.stringify (pessoa, function (key, value) {
var bDate;
if (key == "nascimento") {
bDate = new Date (value)
return ( bDate.getDate() +"/"+
bDate.getMonth()+1 +"/"+ bDate.getFullYear() )
}
return value;
}));
91. Date
●getDate() Retorna um número inteiro entre 1 e 31, que
representa o dia do mês do objeto Date.
●getDay() Retorna um número inteiro do dia da semana.
Domingo 0, segunda 1, terça 2, etc.
●getFullYear() Retorna o ano do objeto Date em números
absolutos, por exemplo 1998.
●getMonth() Retorna o mês do objeto Date, um inteiro entre 0 e
11 (0 janeiro, 1 fevereiro, etc).
93. Compatibilidade
●JavaScript, Jscript, ECMAScript, ActionScript
●ECMAScript é uma linguagem de programação baseada
em scripts, padronizada pela Ecma International na
especificação ECMA-262.
○http://www.ecma-international.org/publications/files/ECMA-ST
/ECMA-262.pdf
●JavaScript, Jscript e ActionScript são dialetos do
ECMAScript
○Usando apenas elementos do ECMAScript, você garante
compatibilidade.
http://www.jslint.com
94. Todos estes conceitos são amplamente
utilizados em bibliotecas e frameworks,
como o JQuery
Closures
Funções de primeira Ordem
“Sobrecarga”
Funções anônimas
Objetos
99. Variáveis Globais
„ JavaScript's biggest problem is its dependence on global
variables, particularly implied global variables. If a variable
is not explicitly declared (usually with the var statement),
then JavaScript assumes that the variable was global. This
can mask misspelled names and other problems.“
●JSLint
100. Variáveis Globais
„ JavaScript's biggest problem is its dependence on global
variables, particularly implied global variables. If a variable
is not explicitly declared (usually with the var statement),
then JavaScript assumes that the variable was global. This
can mask misspelled names and other problems.“
●JSLint
Use sempre o var e declare antes
de usar
108. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide http://www.jslint.com/
109. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide http://www.jslint.com/
Use ponto e vírgula
110. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide http://www.jslint.com/
Use ponto e
virgula
Escopo
111. Escopo
Não existe escopo por bloco, apenas por funções.
function f(p) {
if (p) {
var a = 15
}
console.log (a)
}
f(1)
112. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide
http://www.jslint.com/ Use ponto e
virgula
Escopo
Use
blocos
113. Blocos {}
Uso de blocos evita erros, use sempre mesmo
onde não é obrigatório.
if (condicao) {
..
}
else {
}
114. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide
http://www.jslint.com/ Use ponto e
virgula
Escopo
Use
blocos
115. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
Modularize
Valide
http://www.jslint.com/ Use ponto e
virgula
Escopo
Use
blocos
Comprima
116. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
ModularizeValide
http://www.jslint.co
m/ Use ponto e
virgula
Escop
o
Use
blocos
Comprima
Eval is Evil
117. Boas práticas
Códigos legíveis (nome de
variáveis...)
Variáveis
globais
Opte por notações
curtas
ModularizeValide
http://www.jslint.co
m/ Use ponto e
virgula
Escop
o
Use
blocos
Comprima
Eval is Evil
Consultem o
jslint