javascript basics
Post on 21-Dec-2014
1.743 Views
Preview:
DESCRIPTION
TRANSCRIPT
JAVASCRIPT BASICSRicardo Cavalcanti
kvalcanti@gmail.com
Algumas Ferramentas
“Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while
you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page!”
http://getfirebug.com
O que é Javascript
Uma linguagem de script (leve) Normalmente escrita direto em páginas
HTML Interpretada Desenvolvida para adicionar
interatividade em páginas HTML Validação, comportamento
Grátis, livre de licensa
Javascript é bem mais que validação
A linguagem do browser
Todas as aplicações web usam!
Informações iniciais
Case Sensitive Monothread
TIPOS PRIMITIVOS
Tipos Primitivos
5 tipos primitivos number string boolean null undefined
Todo o resto é object
Tipos Primitivos: number
var n1 = 1;typeof n1
var n2 = 1.5;typeof n2
var n3 = 0100;typeof n3n3
var n4 = 0xFF;typeof n4n4
>> “number”
>> “number”
>> “number”>> 64
>> “number”>> 255
Tipos Primitivos: number
var n5 = 1e1;typeof n5n5
var n6 = 2e+3;typeof n6n6
var n7 = 2e-3;typeof n7n7
>> "number">> 10
>> "number">> 2000
>> "number">> 0.002
Tipos Primitivos: number
var n8 = Infinity;typeof n8n8
var n9 = 1e309;typeof n9n9
var n10 = 6/0;typeof n10n10
var n11 = -1*Infinity;typeof n11n11
>> "number">> Infinity
>> "number">> Infinity
>> "number">> Infinity
>> "number">> -Infinity
Tipos Primitivos: number
var n12 = NaN;typeof n12n12
var n13 = 10 * "string"typeof n13n13
var n14 = 1 + 1 + NaN;typeof n14n14
>> "number">> NaN
>> "number">> NaN
>> "number">> NaN
Tipos Primitivos: string
var s1 = "some string";
typeof s1
var s2 = 'a';typeof s2
var s3 = "10";typeof s3
>> "string"
>> "string"
>> "string"
Tanto faz, aspas duplas ou simples.
Tipos Primitivos: string
var s41 = "one";
var s42 = "two"
var s43 = s41 + s42;
s43
var s51 = "10";
typeof s51
var s52 = s51 * 5;
s52
typeof s52
>> "onetwo"
>> "string"
>> 50
>> "number
Tipos Primitivos: string
var s6 = "1";
typeof s6
++s6
typeof s6
var s7 = "some string 1";
var s71 = s7 * 1;
typeof s7
s71
typeof s71
>> "string"
>> 2
>> "number"
>> "string"
>> NaN
>> "number"
Tipos Primitivos: boolean
var b1 = false;
typeof b1
var b2 = "some string";
var b21 = !b2;
var b22 = !!b2;
typeof b2
b21
typeof b21
b22
typeof b22
>> "boolean"
>> "string"
>> false
>> "boolean"
>> true
>> "boolean"
Tipos Primitivos: boolean
var b31 = "";var b32 = null;var b33 = false;var b34 = NaN;var b35 =
undefined;var b36 = 0;
If ( !b31 ){ //executa}
Tudo é true em javascript, exceto seis valores:
Tipos Primitivos: boolean
!=Diferente:
true se os operandos não forem iguais
Alguns operadores de comparação
!==Diferente sem conversão de
tipo: true se os operandos não
forem iguais OU não forem do mesmo tipo
==Comparador de igualdade:
true se ambos os operandos forem iguais. Converte para o mesmo
tipo antes da comparacao
===Comparador de igualdade e
tipo:true se os operandos
forem iguais e do mesmo tipo
Tipos Primitivos: boolean
var b4 = 2!="2";var b41 = 2=="2";
var b42 = 2!=="2";var b43 =
2==="2";
>> false>> true
>> true>> false
Tipos Primitivos: null
var nl1 = null;typeof nl1nl1
var nl2 = 1 + null;nl2
var nl3 = 1*null;nl3
>> "object">> null
>> 1
>> 0
Tipos Primitivos: undefined
var u1 = {};
typeof u1.campoinexistente
u1. campoinexistente
var u2 = 1 + undefined;
u2
var u3 = 1 * undefined;
u3
>> undefined
>> undefined
>> NaN
>> NaN
Arrays
var a = [1,2,3];
typeof a
a
a[0]
a[5]
a[5] = "some string";
a
delete a[2];
a
delete a[5];
a
>> "object"
>> [1,2,3]
>> 1
>> undefined
>> [1,2,3, undefined, undefined,"some string"]
>> [1,2, undefined, undefined, undefined, "some string"]
>> [1,2, undefined, undefined, undefined, undefined]
Arrays
var a2 = [[1,2,3],
["string1","string2",3]];
a2[0]
a2[1]
var a3 = "one";
typeof a3
a3[0]
typeof a3[0]
a3[1]
>> [1,2,3]
>> ["string1","string2",3]
>> "string"
>> "o"
>> "string"
>> "n"
FUNÇÕES
Funções
Funções são, talvez a coisa mais importante em Javascript
function sum(a,b) {
return a + b;
}
var r1 = sum(1,1); >> 2
Funções: parâmetros
Os parâmetros não passados são undefined
Parâmetros a mais também podem ser passados
function sum(a,b) { return a + b;
}var r2 = sum(1);var r3 =
sum(1,2,3,4,5);
>> NaN {1 + undefined = NaN}
>> 3
Funções: parâmetros
arguments é o array de parâmetros que a função recebe
function sumAll() {
var result = 0;
for(var i=0,length=arguments.length;i<length;i++){
result+=arguments[i];
}
return result;
}
var r4 = sumAll(1,2,3,4,5,6,7);
r4 >> 28
Funções: notação literal
Funções são como uma variável qualquer.
var func3 = function(a,b) {
return a*b;
};
var f3 = func3;
typeof func3 >> "function"
typeof f3 >> "function"
func3(2,2) >> 4
f3(3,3) >> 9
Funções: construtor padrão
var func6 = new Function("a,b","return a+b;");
func6(2,2) >> 4
Não use! Também evite eval() Evite passar código Javascript como uma
string
eval(“var a = 2");++a >> 3
Funções: callbacks
function info(){ alert("funcao info“);
}
function execute(func) { func();
}execute(info);
Funções: funções anônimas
Funções anônimas podem ser passadas como parâmetro E também podem ser definidas para executar
imediatamente
function execute(func) {
func();
}
execute(function() {
alert("hello, anonimo!“);
});
(function(a,b) {
return a-b;
})(5,3);
>> "hello, anonimo“
>>2
Funções: inner functions
Mantêm o global namespace limpo
function funcTop() { var a = function() {
alert("innerFunction: work...");}alert("funcTop: work...");a();
}
Funções: escopo
Variáveis NÃO são definidas no escopo do bloco, e sim no ESCOPO DA FUNÇÃO.
function func() {
var a = "local";
if(true) {
a
var a2 = "local-if";
a2
}
a
a2
}
>> "local"
>> "local-if"
>> "local"
>> "local-if"
Funções: escopo
var r5 = "global";function func1() {
alert(r5); var r5 = "local"; alert(r5);
}func1();
r5 >> undefinedr5 >> "local"
var r5 = "global";function func1() {
out(r5);}func1();
r5 >> "global"
Funções: escopo léxico
Funções tem escopo léxico: elas criam seu ambiente (escopo) quando são definidas, não quando são executadas.
function func4() {
var v = 1;
return func5();
};
function func5() {
return v;
};
func4()>> ReferenceError: v is not
defined
function func41() {
var v = 1;
return (function() {
return v;
})();
};
func41();
>> 1
Funções: escopo léxico
var a;//..function F() {
var b; //.. function N() {
var c; //..
}}
Global
F
N
•a
•b
•c
Funções: escopo léxico
var a;var N;//..function F() {
var b;//.. N = function () { var c; //.. }}
Global
F
N
•a
•b
•c
Depois, um pouco mais sobre escopo de funções e closures
JS OBJECTS
String, Date, RegExp, Math
JS Objects
Já existem alguns objetos definidos Array Boolean Date Math Number String RegExp Global
JS Objects: Array
concat() join() pop() push() reverse() …
JS Objects: Date
Para instanciarnew Date() // current date and timenew Date(milliseconds) //milliseconds since
1970/01/01new Date(dateString)new Date(year, month, day, hours, minutes,
seconds, milliseconds) Podem ser comparadas com < e > Diversos métodos para manipulação
setFullYear(), getMinutes()...
JS Objects: Math
Para tarefas matemáticas round(), max(), min(), random()
Algumas constantes Math.E, Math.PI, Math.SQRT2,
Math.SQRT1_2, Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E
JS Objects: String
charAt() concat() fromCharCode() indexOf() lastIndexOf() match() replace()
search() slice() split() substr() substring() toLowerCase() toUpperCase()
JS Objects: regexp
Sintaxevar txt=new RegExp(pattern,modifiers);var txt=/pattern/modifiers;
Modificadores i : case-sensitive g: global match, acha todos, não apenas a primeira m: multiline
Uso comum String.match()var str="Is this all there is?";var patt1=/is/gi;Is this all there is?
JS Objects: global
Define algumas constantes NaN e Infinity
Algumas funções auxiliares escape(), unescape() isFinite(), isNaN() parseFloat(), parseInt()
OBJECTS
Objects
Objetos representam arrays associativos (hashes)
Um objeto é um container de propriedades
Não têm classe Mas pode haver herança!
Podem ser aumentados a qualquer hora
Objetos: arrays associativos
var obj = {
prop:1,
prop2:"string",
"unusual-prop":"value",
'WTF?$#!@$':{
a:"a-val"
},
array: [1,2,3]
};
typeof obj >> object
obj.prop >> obj["unusual-prop"] >> "value"
obj['WTF?$#!@$'].a >> "a-val"
obj.array >> [1,2,3]
obj["array"] >> [1,2,3]
Objects: Literais
Propriedades podem ser qualquer valor, exceto undefined O nome de uma propriedade pode ser qualquer string,
inclusive “”
var empty_object = {};
var person = {
"first-name": "Jerome",
"last-name": "Howard"
};
var flight = {
airline: "Oceanic",
number: 815,
departure: {
time: "2004-09-22 14:55",
city: "Sydney"
},
arrival: {
time: "2004-09-23 10:42",
city: "Los Angeles"
}
};
Objects: “namespaces”
Boa prática para evitar conflitos
var MYAPP = {};
MYAPP.person = { "first-name": "Joe", "last-name": "Howard" };
Objects: acesso
[], como um arrayperson["first-name"]
Usando dot-notationflight.departure.city
Propriedades inexistentes >> undefined || para definir valores default
var status = flight.status || "unknown"; Acesso a um undefined lança TypeError
flight.equipment // undefined flight.equipment.model // throw "TypeError"
Objects: Atualização
var obj = { prop:1, prop2:"string", "unusual-prop":"value", 'WTF?$#!@$':{
a:"a-val" }, array: [1,2,3]
};
obj.prop3 >> undefined
obj.prop3 = "value3";
obj.prop3 >> "value3"
Objects: referência
Objetos sempre são passados por referencia
var obj1 = {
a:"val-a"
};
var obj2 = obj1;
obj1.a >> "val-a"
obj2.a >> "val-a“
obj2.a = "val-a2“;
obj1.a >> "val-a2"
obj2.a >> "val-a2"
var obj3 = {
a:"val-a"
};
obj1===obj2 >> true
obj1===obj3 >> false
var a = {}, b = {}, c = {};
//todos diferentes
a = b = c = {};
//todos o mesmo objeto vazio
Objects: Funções
var dog = { name: "Bobik", talk: function() {
return "Woof, woof!"; }, sayName: function() {
return this.name; }
};
dog.name >> "Bobik"
dog.talk() >> "Woof, woof!"
dog.sayName() >> "Bobik"
Objects: Construtor
function Cat(/*String*/ name) { this.name = name; this.talk = function() {
return "I'm "+this.name+". Mrrr, miaow!"; }
}var cat = new Cat("Barsik");typeof cat >> objectcat.name >> "Barsik"cat.talk() >> "I’m Barsik. Mrrr, miaow!"
Objects: Construtor
function Cat(/*String*/ name) { this.name = name; this.talk = function() { //... }
}var cat2 = Cat("Barsik");
Chamada sem new
This faz referencia ao objeto global window
typeof cat2 >> undefinedcat2.name >> TypeError: cat2 has no properties
window.name >> "Barsik"
Objects: Construtor
Quando um objeto é criado, a propriedade constructor é definida
var cat = new Cat("Barsik");var constr = cat.constructor;var cat3 = cat.constructor("Murzik");
constr >> function Cat(name) { .... }cat3.talk() >> "I’m Murzik. Mrrr, miaow!"
Objects: call e apply
Todo objeto tem dois métodos: call() e apply()
var cat = new Cat("Barsik");
//..
var cat4 = {name:"Agatha"};
cat.talk.call(cat4/**, param1, p2, ... **/) >> "I’m Agatha. Mrrr, miaow!"
cat.talk.apply(cat4/**, [param1, p2, ...] **/) >> "I’m Agatha. Mrrr, miaow!"
Objects: instanceof
Instanceof testa se o objeto foi criado com um constutor específico
var cat = new Cat("Barsik");var o = {};
cat instanceof Cat >> truecat instanceof Object >> true
o instanceof Object >> trueo instanceof Cat >> false
top related