JavascriptBasicsRicardo Cavalcantikvalcanti@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 é JavascriptUma linguagem de script (leve)Normalmente escrita direto em páginas HTMLInterpretadaDesenvolvida para adicionar interatividade em páginas HTMLValidação, comportamentoGrátis, livre de licensa
Javascript é bem mais que validaçãoA linguagem do browserTodas as aplicações web usam!
Informações iniciaisCase SensitiveMonothread
Tipos Primitivos
Tipos Primitivos5 tipos primitivosnumberstringbooleannullundefinedTodo o resto é object
Tipos Primitivos: numbervar n1 = 1;typeof n1var n2 = 1.5;typeof n2var n3 = 0100;typeof n3n3var n4 = 0xFF;typeof n4n4>> “number”>> “number”>> “number”>> 64>> “number”>> 255
Tipos Primitivos: numbervar 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: numbervar n8 = Infinity;typeof n8n8var n9 = 1e309;typeof n9n9var n10 = 6/0;typeof n10n10var n11 = -1*Infinity;typeof n11n11>> "number">> Infinity>> "number">> Infinity>> "number">> Infinity>> "number">> -Infinity
Tipos Primitivos: numbervar n12 = NaN;typeof n12n12var n13 = 10 * "string"typeof n13n13var n14 = 1 + 1 + NaN;typeof n14n14>> "number">> NaN>> "number">> NaN>> "number">> NaN
Tipos Primitivos: stringvar s1 = "some string";typeof s1var s2 = 'a';typeof s2var s3 = "10";typeof s3>> "string">> "string">> "string"Tanto faz, aspas duplas ou simples.
Tipos Primitivos: stringvar s41 = "one";var s42 = "two"var s43 = s41 + s42;s43var s51 = "10";typeof s51var s52 = s51 * 5;s52typeof s52>> "onetwo">> "string" >> 50>> "number
Tipos Primitivos: stringvar s6 = "1";typeof s6++s6typeof s6var s7 = "some string 1";var s71 = s7 * 1;typeof s7s71typeof s71>> "string">> 2>> "number">> "string">> NaN>> "number"
Tipos Primitivos: booleanvar b1 = false;typeof b1var b2 = "some string";var b21 = !b2;var b22 = !!b2;typeof b2b21typeof b21b22typeof b22>> "boolean">> "string">> false>> "boolean">> true>> "boolean"
Tipos Primitivos: booleanTudo é true em javascript, exceto seis valores:var b31 = "";var b32 = null;var b33 = false;var b34 = NaN;var b35 = undefined;var b36 = 0;If ( !b31 ){ //executa}
Tipos Primitivos: booleanAlguns operadores de comparação!=Diferente:true se os operandos não forem iguais==Comparador de igualdade:true se ambos os operandos forem iguais. Converte para o mesmo tipo antes da comparacao!==Diferente sem conversão de tipo: true se os operandos não forem iguais OU não forem do mesmo tipo===Comparador de igualdade e tipo:true se os operandos forem iguais e do mesmo tipo
Tipos Primitivos: booleanvar b4 = 2!="2";var b41 = 2=="2";var b42 = 2!=="2";var b43 = 2==="2";>> false>> true>> true>> false
Tipos Primitivos: nullvar nl1 = null;typeof nl1nl1var nl2 = 1 + null;nl2var nl3 = 1*null;nl3 >> "object">> null>> 1>> 0
Tipos Primitivos: undefinedvar u1 = {}; typeof u1.campoinexistenteu1. campoinexistentevar u2 = 1 + undefined; u2var u3 = 1 * undefined;u3>> undefined>> undefined >> NaN>> NaN
Arraysvar a = [1,2,3];typeof aaa[0]a[5]a[5] = "some string";adelete a[2];adelete 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]
Arraysvar a2 = [[1,2,3],["string1","string2",3]];a2[0]a2[1]var a3 = "one";typeof a3a3[0]typeof a3[0]a3[1]>> [1,2,3]>> ["string1","string2",3]>> "string" >> "o">> "string">> "n"
Funções
FunçõesFunções são, talvez a coisa mais importante em Javascriptfunction sum(a,b) {	 return a + b;}var r1 = sum(1,1);>> 2
Funções: parâmetrosOs parâmetros não passados são undefinedParâmetros a mais também podem ser passadosfunction 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âmetrosargumentsé o array de parâmetros que a função recebefunction sumAll() {var result = 0;	 for(vari=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 literalFunçõ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ãovar func6 = new Function("a,b","returna+b;");func6(2,2) >> 4Não use! Tambémeviteeval()EvitepassarcódigoJavascriptcomouma stringeval(“var a = 2");++a                       >> 3
Funções: callbacksfunction info(){	 alert("funcao info“);}function execute(func) {func();}execute(info);
Funções: funções anônimasFunções anônimas podem ser passadas como parâmetroE também podem ser definidas para executar imediatamentefunction execute(func) {func();}execute(function() {    alert("hello,  anonimo!“);});(function(a,b) {return a-b;})(5,3);>> "hello, anonimo“>>2
Funções: innerfunctionsMantêm o global namespace limpofunction funcTop() {var a = function() {		alert("innerFunction: work...");	}	alert("funcTop: work...");	a();}
Funções: escopoVariáveis NÃO são definidas no escopo do bloco, e sim no ESCOPO DA FUNÇÃO.function func() {var a = "local";	 if(true) {		 avar a2 = "local-if";		 a2	 }	 a	 a2}>> "local">> "local-if">> "local">> "local-if"
Funções: escopovar 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éxicoFunçõ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 definedfunction func41() {var v = 1;	 return (function() {		 return v;	 })();	};func41();>> 1
Funções: escopo léxicovar a;//..function F() {	 var b;	 //..function N() {		 var c;		 //..	 }}GlobalaFbNcFunções: escopo léxicovar a;var N;//..function F() {	 var b;//..    N = function () {     var c;    //..    }}GlobalaFbNcDepois, um pouco mais sobre escopo de funções e closures
JS ObjectsString, Date, RegExp, Math
JS ObjectsJá existem alguns objetos definidosArrayBooleanDateMathNumberStringRegExpGlobal
JS Objects: Arrayconcat()join()pop()push()reverse()…
JS Objects: DatePara 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 >DiversosmétodosparamanipulaçãosetFullYear(),  getMinutes()...
JS Objects: MathPara tarefas matemáticasround(), max(), min(), random()Algumas constantesMath.E, Math.PI, Math.SQRT2, Math.SQRT1_2, Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E
JS Objects: StringcharAt()concat()fromCharCode()indexOf()lastIndexOf()match()replace()search()slice()split()substr()substring()toLowerCase()toUpperCase()
JS Objects: regexpSintaxevar txt=new RegExp(pattern,modifiers);var txt=/pattern/modifiers;Modificadoresi : case-sensitiveg: global match, achatodos, nãoapenas a primeiram: multilineUsocomumString.match()varstr="Is this all there is?";var patt1=/is/gi;Is this all there is?
JS Objects: globalDefine algumas constantesNaN e InfinityAlgumas funções auxiliaresescape(), unescape()isFinite(), isNaN()parseFloat(), parseInt()
Objects
ObjectsObjetos representam arrays associativos (hashes)Um objeto é um container de propriedadesNão têm classeMas pode haver herança!Podem ser aumentados a qualquer hora
Objetos: arrays associativosvarobj = {	 prop:1,	 prop2:"string",	 "unusual-prop":"value",	 'WTF?$#!@$':{		 a:"a-val"	 },	 array: [1,2,3]	};typeofobj >> objectobj.prop >> obj["unusual-prop"] >> "value" obj['WTF?$#!@$'].a >> "a-val"obj.array >> [1,2,3]obj["array"] >> [1,2,3]
Objects: LiteraisPropriedades podem ser qualquer valor, exceto undefinedO 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 conflitosvar MYAPP = {};MYAPP.person = {      "first-name": "Joe",      "last-name": "Howard" };
Objects: acesso[],  como um arrayperson["first-name"]Usando dot-notationflight.departure.cityPropriedades inexistentes >> undefined|| para definir valores default	var status = flight.status || "unknown";Acesso a um undefined lança TypeErrorflight.equipment // undefined flight.equipment.model // throw "TypeError"
Objects: Atualizaçãovarobj = {	 prop:1,	 prop2:"string",	 "unusual-prop":"value",	 'WTF?$#!@$':{		 a:"a-val"	 },	 array: [1,2,3]	};obj.prop3 >> undefinedobj.prop3 = "value3";obj.prop3 >> "value3"
Objects: referênciaObjetos sempre são passados por referenciavar 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 >> trueobj1===obj3 >> falsevar a = {}, b = {}, c = {};    //todos diferentesa = b = c = {};  //todos o mesmo objeto vazio
Objects: Funçõesvar dog = {name: "Bobik",talk: function() {return "Woof, woof!";	 },sayName: function() {returnthis.name;	 }};dog.name >> "Bobik" dog.talk() >> "Woof, woof!"dog.sayName() >> "Bobik"
Objects: ConstrutorfunctionCat(/*String*/ name) {this.name = name;this.talk = function() {return "I'm "+this.name+". Mrrr, miaow!";	 }}var cat = newCat("Barsik");typeofcat >> objectcat.name >> "Barsik"cat.talk() >> "I’mBarsik. Mrrr, miaow!"
Objects: Construtorfunction Cat(/*String*/ name) {	 this.name = name;this.talk = function() {		 //...	 }}var cat2 = Cat("Barsik");This faz referencia ao objeto global windowChamada sem newtypeof cat2 >> undefinedcat2.name >> TypeError: cat2 has no propertieswindow.name >> "Barsik"
Objects: ConstrutorQuando um objeto é criado, a propriedade constructoré definidavar cat = newCat("Barsik");var constr = cat.constructor;var cat3 = cat.constructor("Murzik");constr >> functionCat(name) { .... }cat3.talk() >> "I’mMurzik. Mrrr, miaow!"
Objects: call e applyTodo objeto tem dois métodos: call() e apply()var cat = newCat("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: instanceofInstanceof testa se o objeto foi criado com um constutor específicovar cat = newCat("Barsik");var o = {};catinstanceofCat >>  truecatinstanceofObject >>  trueo instanceofObject >>  trueo instanceofCat >>  false
Javascript basics

Javascript basics

  • 1.
  • 2.
    Algumas Ferramentas“Firebug integrateswith 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
  • 3.
    O que éJavascriptUma linguagem de script (leve)Normalmente escrita direto em páginas HTMLInterpretadaDesenvolvida para adicionar interatividade em páginas HTMLValidação, comportamentoGrátis, livre de licensa
  • 4.
    Javascript é bemmais que validaçãoA linguagem do browserTodas as aplicações web usam!
  • 5.
  • 6.
  • 7.
    Tipos Primitivos5 tiposprimitivosnumberstringbooleannullundefinedTodo o resto é object
  • 8.
    Tipos Primitivos: numbervarn1 = 1;typeof n1var n2 = 1.5;typeof n2var n3 = 0100;typeof n3n3var n4 = 0xFF;typeof n4n4>> “number”>> “number”>> “number”>> 64>> “number”>> 255
  • 9.
    Tipos Primitivos: numbervarn5 = 1e1;typeof n5n5 var n6 = 2e+3;typeof n6n6 var n7 = 2e-3;typeof n7n7>> "number">> 10 >> "number">> 2000 >> "number">> 0.002
  • 10.
    Tipos Primitivos: numbervarn8 = Infinity;typeof n8n8var n9 = 1e309;typeof n9n9var n10 = 6/0;typeof n10n10var n11 = -1*Infinity;typeof n11n11>> "number">> Infinity>> "number">> Infinity>> "number">> Infinity>> "number">> -Infinity
  • 11.
    Tipos Primitivos: numbervarn12 = NaN;typeof n12n12var n13 = 10 * "string"typeof n13n13var n14 = 1 + 1 + NaN;typeof n14n14>> "number">> NaN>> "number">> NaN>> "number">> NaN
  • 12.
    Tipos Primitivos: stringvars1 = "some string";typeof s1var s2 = 'a';typeof s2var s3 = "10";typeof s3>> "string">> "string">> "string"Tanto faz, aspas duplas ou simples.
  • 13.
    Tipos Primitivos: stringvars41 = "one";var s42 = "two"var s43 = s41 + s42;s43var s51 = "10";typeof s51var s52 = s51 * 5;s52typeof s52>> "onetwo">> "string" >> 50>> "number
  • 14.
    Tipos Primitivos: stringvars6 = "1";typeof s6++s6typeof s6var s7 = "some string 1";var s71 = s7 * 1;typeof s7s71typeof s71>> "string">> 2>> "number">> "string">> NaN>> "number"
  • 15.
    Tipos Primitivos: booleanvarb1 = false;typeof b1var b2 = "some string";var b21 = !b2;var b22 = !!b2;typeof b2b21typeof b21b22typeof b22>> "boolean">> "string">> false>> "boolean">> true>> "boolean"
  • 16.
    Tipos Primitivos: booleanTudoé true em javascript, exceto seis valores:var b31 = "";var b32 = null;var b33 = false;var b34 = NaN;var b35 = undefined;var b36 = 0;If ( !b31 ){ //executa}
  • 17.
    Tipos Primitivos: booleanAlgunsoperadores de comparação!=Diferente:true se os operandos não forem iguais==Comparador de igualdade:true se ambos os operandos forem iguais. Converte para o mesmo tipo antes da comparacao!==Diferente sem conversão de tipo: true se os operandos não forem iguais OU não forem do mesmo tipo===Comparador de igualdade e tipo:true se os operandos forem iguais e do mesmo tipo
  • 18.
    Tipos Primitivos: booleanvarb4 = 2!="2";var b41 = 2=="2";var b42 = 2!=="2";var b43 = 2==="2";>> false>> true>> true>> false
  • 19.
    Tipos Primitivos: nullvarnl1 = null;typeof nl1nl1var nl2 = 1 + null;nl2var nl3 = 1*null;nl3 >> "object">> null>> 1>> 0
  • 20.
    Tipos Primitivos: undefinedvaru1 = {}; typeof u1.campoinexistenteu1. campoinexistentevar u2 = 1 + undefined; u2var u3 = 1 * undefined;u3>> undefined>> undefined >> NaN>> NaN
  • 21.
    Arraysvar a =[1,2,3];typeof aaa[0]a[5]a[5] = "some string";adelete a[2];adelete 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]
  • 22.
    Arraysvar a2 =[[1,2,3],["string1","string2",3]];a2[0]a2[1]var a3 = "one";typeof a3a3[0]typeof a3[0]a3[1]>> [1,2,3]>> ["string1","string2",3]>> "string" >> "o">> "string">> "n"
  • 23.
  • 24.
    FunçõesFunções são, talveza coisa mais importante em Javascriptfunction sum(a,b) { return a + b;}var r1 = sum(1,1);>> 2
  • 25.
    Funções: parâmetrosOs parâmetrosnão passados são undefinedParâmetros a mais também podem ser passadosfunction sum(a,b) { return a + b;}var r2 = sum(1);var r3 = sum(1,2,3,4,5);>> NaN{1 + undefined = NaN}>> 3
  • 26.
    Funções: parâmetrosargumentsé oarray de parâmetros que a função recebefunction sumAll() {var result = 0; for(vari=0,length=arguments.length;i<length;i++){ result+=arguments[i]; } return result;}var r4 = sumAll(1,2,3,4,5,6,7);r4 >> 28
  • 27.
    Funções: notação literalFunçõessã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
  • 28.
    Funções: construtor padrãovarfunc6 = new Function("a,b","returna+b;");func6(2,2) >> 4Não use! Tambémeviteeval()EvitepassarcódigoJavascriptcomouma stringeval(“var a = 2");++a >> 3
  • 29.
    Funções: callbacksfunction info(){ alert("funcao info“);}function execute(func) {func();}execute(info);
  • 30.
    Funções: funções anônimasFunçõesanônimas podem ser passadas como parâmetroE também podem ser definidas para executar imediatamentefunction execute(func) {func();}execute(function() { alert("hello, anonimo!“);});(function(a,b) {return a-b;})(5,3);>> "hello, anonimo“>>2
  • 31.
    Funções: innerfunctionsMantêm oglobal namespace limpofunction funcTop() {var a = function() { alert("innerFunction: work..."); } alert("funcTop: work..."); a();}
  • 32.
    Funções: escopoVariáveis NÃOsão definidas no escopo do bloco, e sim no ESCOPO DA FUNÇÃO.function func() {var a = "local"; if(true) { avar a2 = "local-if"; a2 } a a2}>> "local">> "local-if">> "local">> "local-if"
  • 33.
    Funções: escopovar 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"
  • 34.
    Funções: escopo léxicoFunçõestem 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 definedfunction func41() {var v = 1; return (function() { return v; })(); };func41();>> 1
  • 35.
    Funções: escopo léxicovara;//..function F() { var b; //..function N() { var c; //.. }}GlobalaFbNcFunções: escopo léxicovar a;var N;//..function F() { var b;//.. N = function () { var c; //.. }}GlobalaFbNcDepois, um pouco mais sobre escopo de funções e closures
  • 36.
  • 37.
    JS ObjectsJá existemalguns objetos definidosArrayBooleanDateMathNumberStringRegExpGlobal
  • 38.
  • 39.
    JS Objects: DateParainstanciarnew 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 >DiversosmétodosparamanipulaçãosetFullYear(), getMinutes()...
  • 40.
    JS Objects: MathParatarefas matemáticasround(), max(), min(), random()Algumas constantesMath.E, Math.PI, Math.SQRT2, Math.SQRT1_2, Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E
  • 41.
  • 42.
    JS Objects: regexpSintaxevartxt=new RegExp(pattern,modifiers);var txt=/pattern/modifiers;Modificadoresi : case-sensitiveg: global match, achatodos, nãoapenas a primeiram: multilineUsocomumString.match()varstr="Is this all there is?";var patt1=/is/gi;Is this all there is?
  • 43.
    JS Objects: globalDefinealgumas constantesNaN e InfinityAlgumas funções auxiliaresescape(), unescape()isFinite(), isNaN()parseFloat(), parseInt()
  • 44.
  • 45.
    ObjectsObjetos representam arraysassociativos (hashes)Um objeto é um container de propriedadesNão têm classeMas pode haver herança!Podem ser aumentados a qualquer hora
  • 46.
    Objetos: arrays associativosvarobj= { prop:1, prop2:"string", "unusual-prop":"value", 'WTF?$#!@$':{ a:"a-val" }, array: [1,2,3] };typeofobj >> objectobj.prop >> obj["unusual-prop"] >> "value" obj['WTF?$#!@$'].a >> "a-val"obj.array >> [1,2,3]obj["array"] >> [1,2,3]
  • 47.
    Objects: LiteraisPropriedades podemser qualquer valor, exceto undefinedO 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" } };
  • 48.
    Objects: “namespaces”Boa práticapara evitar conflitosvar MYAPP = {};MYAPP.person = { "first-name": "Joe", "last-name": "Howard" };
  • 49.
    Objects: acesso[], como um arrayperson["first-name"]Usando dot-notationflight.departure.cityPropriedades inexistentes >> undefined|| para definir valores default var status = flight.status || "unknown";Acesso a um undefined lança TypeErrorflight.equipment // undefined flight.equipment.model // throw "TypeError"
  • 50.
    Objects: Atualizaçãovarobj ={ prop:1, prop2:"string", "unusual-prop":"value", 'WTF?$#!@$':{ a:"a-val" }, array: [1,2,3] };obj.prop3 >> undefinedobj.prop3 = "value3";obj.prop3 >> "value3"
  • 51.
    Objects: referênciaObjetos sempresão passados por referenciavar 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 >> trueobj1===obj3 >> falsevar a = {}, b = {}, c = {}; //todos diferentesa = b = c = {}; //todos o mesmo objeto vazio
  • 52.
    Objects: Funçõesvar dog= {name: "Bobik",talk: function() {return "Woof, woof!"; },sayName: function() {returnthis.name; }};dog.name >> "Bobik" dog.talk() >> "Woof, woof!"dog.sayName() >> "Bobik"
  • 53.
    Objects: ConstrutorfunctionCat(/*String*/ name){this.name = name;this.talk = function() {return "I'm "+this.name+". Mrrr, miaow!"; }}var cat = newCat("Barsik");typeofcat >> objectcat.name >> "Barsik"cat.talk() >> "I’mBarsik. Mrrr, miaow!"
  • 54.
    Objects: Construtorfunction Cat(/*String*/name) { this.name = name;this.talk = function() { //... }}var cat2 = Cat("Barsik");This faz referencia ao objeto global windowChamada sem newtypeof cat2 >> undefinedcat2.name >> TypeError: cat2 has no propertieswindow.name >> "Barsik"
  • 55.
    Objects: ConstrutorQuando umobjeto é criado, a propriedade constructoré definidavar cat = newCat("Barsik");var constr = cat.constructor;var cat3 = cat.constructor("Murzik");constr >> functionCat(name) { .... }cat3.talk() >> "I’mMurzik. Mrrr, miaow!"
  • 56.
    Objects: call eapplyTodo objeto tem dois métodos: call() e apply()var cat = newCat("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!"
  • 57.
    Objects: instanceofInstanceof testase o objeto foi criado com um constutor específicovar cat = newCat("Barsik");var o = {};catinstanceofCat >> truecatinstanceofObject >> trueo instanceofObject >> trueo instanceofCat >> false