SlideShare une entreprise Scribd logo
1  sur  174
Javascript
     do jeito certo


     Alexandre Gomes
javascript
                      ?
a 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
http://corte.si/posts/code/devsurvey/index.html
https://github.com/blog/99-popular-languages
javascript
Afinal,



         é do mal ou do bem?
http://www.ecma-international.org/publications/standards/Ecma-262.htm
ISO IEC
                     16262


http://www.ecma-international.org/publications/standards/Ecma-262.htm
“         ECMAScript is an
         object-oriented
          programming
       language for performing
    computations and manipulating
     computational objects within
         a host environment.

          ECMAScript Language Specification
            5th edition (December 2009)
“      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
              5th edition (December 2009)
“       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
              5th edition (December 2009)
“        Some of the facilities of
     ECMAScript are similar to those
       used in other programming
    languages; in particular Java  TM,
            Self, and Scheme


           ECMAScript Language Specification
             5th edition (December 2009)
“   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
               5th edition (December 2009)
“     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
                5th edition (December 2009)
“           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
                  5th edition (December 2009)
“   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
             5th edition (December 2009)
“   Each Web browser and server that
       supports ECMAScript supplies
     its own host environment,
        completing the ECMAScript
          execution environment.


           ECMAScript Language Specification
             5th edition (December 2009)
“   ECMAScript is an object-oriented
    programming language
                           (...)




          ECMAScript Language Specification
            5th edition (December 2009)
“     ECMAScript is an object-oriented
      programming language
                                 (...)


      Tipos    Boolean, Number, String, Array, RegExp


Operadores     + - * / >> << >>> < > <= >= | & *= ^ ++

Comentários    //    /*       */

  Estruturas   do while for if else try catch switch



                ECMAScript Language Specification
                  5th edition (December 2009)
Tipos
          (construtores)



Boolean                    Object
Number                Function
String                     RegExp
 Array                      Date
Tipos
              undefined




var x;
alert(x);




       ECMAScript Language Specification
         5th edition (December 2009)
Tipos
                   null




var x = null;
alert(x);




       ECMAScript Language Specification
         5th edition (December 2009)
Tipos
                             Boolean



var x = true;
if(x) {
  alert('Verdadeiro');
}

Obs: 0 e null equivalem a false




                   ECMAScript Language Specification
                     5th edition (December 2009)
Tipos
                 Number


var x = 10;
var y = 15;
alert(x+y);


var x = 10.1;
var y = 15.2;
alert(x+y);


        ECMAScript Language Specification
          5th edition (December 2009)
Tipos
                 String



var x = “Alexandre”;
alert(x);




      ECMAScript Language Specification
        5th edition (December 2009)
Tipos
                  Function


var x = function() { alert("Alexandre"); };
x();




          ECMAScript Language Specification
            5th edition (December 2009)
> 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 Boolean(true);
if(x) { alert('Verdadeiro'); }




var x = new String(“Alexandre”);
alert(x);




var x = new Number(10);
var y = new Number(15);
alert(x+y);
Operadores
             /        <<=   ? :
delete
             %        >>=    =
 void
             >>        ==    *=
typeof
             <<       !=     /=
  ++
            >>>       ===    %=
  --
             <        !==    +=
  +
             >         &     -=
  -
             <=        ^    >>>=
  ~
             >=        |     &=
  !
         instanceof   &&     ˆ=
  *                   ||
             in              |=
Operadores
                   delete

var a = 1
undefined
a
1
delete a
true
a
ReferenceError: a is not defined
           ECMAScript Language Specification
             5th edition (December 2009)
Operadores
                        typeof

typeof 1
"number"
typeof true
"boolean"
typeof "Alexandre"
"string"
typeof function() { alert('Oi') }
"function"
typeof null
"object"
                ECMAScript Language Specification
                  5th edition (December 2009)
Operadores
                   ++ e --

var a = 1
undefined
a++
1
a
2
++a
3
            ECMAScript Language Specification
              5th edition (December 2009)
Operadores
                 instanceof

var a = "alexandre"
undefined
a instanceof String
false
var a = new String("alexandre")
undefined
a instanceof String
true
a instanceof Object
true
              ECMAScript Language Specification
                5th edition (December 2009)
Operadores
            ==, !=, ===, !==

3 == "3"
true
3 === "3"
false

2 != "2"
false
2 !== "2"
true
             ECMAScript Language Specification
               5th edition (December 2009)
Estruturas


if/else    continue      switch
do/while     break        throw
 while      return      try/catch
  for        with       debugger
 for/in
Estruturas
                   if/else

var a = true

if (a) {
  alert('Verdadeiro')
} else {
  alert('Falso')
}
            ECMAScript Language Specification
              5th edition (December 2009)
Estruturas
               do/while


var i = 1
do {
  alert(i);                                  (...)

  i++;
} while (i < 5)

          ECMAScript Language Specification
            5th edition (December 2009)
Estruturas
                        for


for ( var i = 1; i < 5; i++) {
  alert(i);
}


                       (...)



            ECMAScript Language Specification
              5th edition (December 2009)
Estruturas
                       for/in

var array = [1,3,5,7,9]

for (var i in array) {
  alert(array[i])
}


                          (...)



               ECMAScript Language Specification
                 5th edition (December 2009)
Estruturas
                    for/each/in
> 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
 }
                  ECMAScript Language Specification
                    5th edition (December 2009)
Estruturas
                            with

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
}
                  ECMAScript Language Specification
                    5th edition (December 2009)
Estruturas
                         switch/case
var a = "alexandre";

switch (a) {

case "sebastiao":
 alert("Tião?");
 break;

case "raimunda":
 alert("Raimundinha?");
 break;

 case "alexandre":
  alert("Alê!");
  break;
}
                       ECMAScript Language Specification
                         5th edition (December 2009)
“      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
objetos definidos pela   objetos definidos pelo   objetos definidos pelo
 especificação           web browser             desenvolvedor
 ECMAScript

     Boolean                 window                 alexandre
     Number                 document               mensagem
      String            XMLHttpRequest                   ...
      Array                      ...
       ...
“            An ECMAScript object is a
         collection of properties
      each with zero or more attributes
    that determine how each property can be used

                    alexandre


             nome: “Alexandre”
             sobrenome: “Gomes”
             idade: 34




            ECMAScript Language Specification
              5th edition (December 2009)
“            An ECMAScript object is a
         collection of properties
      each with zero or more attributes
    that determine how each property can be used

                    alexandre


             nome: “Alexandre”
             sobrenome: “Gomes”
             idade: 34
                   modificável: false



            ECMAScript Language Specification
              5th edition (December 2009)
> 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.


                     alexandre

    nome: “Alexandre”
    nascimento: new Date(1977,8,8,0,0,0,0)
    idade: function() { ... }




             ECMAScript Language Specification
               5th edition (December 2009)
“   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.length
                                    String
9
> 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>"
Boolean
>>> var x = true;
>>> if(x) { alert('yes'); } else { alert('no') } // yes

>>> !x
false

>>> x   & false
0
>>> x   && false
false
>>> x   | false
1
>>> x   || false
true

>>> var x = false;
>>> if(x) { alert('yes'); } else { alert('no') } // no
Number
>>> var x = 10
>>> var y = 15;
>>> z = x + y
25

>>> z.toFixed(2);
"25.00"

>>> z.toExponential(2);
"2.50e+1"

>>> 2.toExponential(2);
SyntaxError: identifier starts immediately
after numeric literal
Math
>>> Math.PI
3.141592653589793
>>> Math.sqrt(81);
9
>>> Math.tan(45);
1.6197751905438615
>>> Math.pow(3,2);
9
>>> Math.random();
0.8528815588353642
>>> Math.random();
0.955940929887219
>>> var x = new Date();                                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)"
>>> var x = new Date();
>>> x.toString();
                                                       Date
"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)"
>>> var texto = "O gato roeu a roupa do rei de roma";
>>> var regex = new RegExp("gato", “”);

>>> texto.match(regex);
["gato"]
                                            Regex
>>> 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"]
>>> var obj = { "nome": "Alexandre", "idade" : "33" }
>>> obj.constructor;
Object()                                                  JSON
>>> 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"
var x = new Array();
>>> []                                    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
“    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...
“   apesar de ser OO,

 ECMAScript does not use
classes such as those in C+
    +, Smalltalk, or Java.




                   ECMAScript Language Specification
                     5th edition (December 2009)
“Classful”             “Classless”
reuso por herança de    reuso por clonagem
       classes              de objetos


      Pessoa                   joao

       nome                 nome: “João”
       sexo                  idade: 28


            <<herda>>                 <<clona>>

     Funcionári               maria
         o
       salário             nome: “Maria”
                             idade: 20
“Classful”                “Classless”
   modelagem                 modelagem
   top-down                  bottom-up




primeiro a taxonomia e        primeiro o
seus relacionamentos...    comportamento...
“Classful”           “Classless”

objetos criados a      objetos criados a
partir de classes    partir de clonagem...


hoje = new Date()   hoje = new Date()


                      ...ou por ‘geração
                          expontânea’
                    var x = {
                      one: 1,
                      two: 2
                    }
“Classful”            “Classless”


objetos carregam a   objetos carregam as
   estrutura e o      características de
 comportamento
   de sua classe      seu protótipo
Programação baseada em

   protótipos


protótipo
Programação baseada em

   protótipos


protótipo               clone
Programação baseada em

   protótipos


protótipo               clone
Programação baseada em

              protótipos
>>> var conta = { saldo: 1000.00 };
>>> conta.saldo
1000
>>> conta.limite
undefined

>>> var conta_especial = { limite: 500.00 }
>>> conta_especial.limite
500
>>> conta_especial.saldo
undefined

>>> conta_especial.__proto__ = conta // referência explícita
Object { saldo=1000}
>>> conta_especial.saldo
1000
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
      var conta = { saldo: 1000.00 }




          ECMAScript Language Specification
            5th edition (December 2009)
“   objects may be created in
     various ways including
      via a literal notation
      var conta = { saldo: 1000.00 }


       or via constructors
      hoje = new Date()
          ECMAScript Language Specification
            5th edition (December 2009)
“   Each constructor
      is a function
       hoje = new Date()


    function Date() {
    ...
    }

      ECMAScript Language Specification
        5th edition (December 2009)
mas
    function é também um
            objeto

                          Date()
var Date = function() {
...
}

hoje = new Date()
construtor


 function    Date()




 objeto
construtor


 function      Date()




  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”(...)



     Date()
    <<construtor

     prototype




                               Protótipo
                               do Date()


                   ECMAScript Language Specification
                     5th edition (December 2009)
Date()
<<construtor

prototype




                           Protótipo
                           do Date()


               ECMAScript Language Specification
                 5th edition (December 2009)
“   Every object created by a constructor




     Date()
    <<construtor      hoje = new Date()               hoje
    prototype




                               Protótipo
                               do Date()


                   ECMAScript Language Specification
                     5th edition (December 2009)
“   Every object created by a constructor
    has an implicit reference (called the object’s prototype)




     Date()
     <<construtor      hoje = new Date()                hoje
     prototype                                         prototype




                                Protótipo
                                do Date()


                    ECMAScript Language Specification
                      5th edition (December 2009)
“   Every object created by a constructor
    has an implicit reference (called the object’s prototype)
     to the value of its constructor’s “prototype” property.



     Date()
     <<construtor      hoje = new Date()                hoje
     prototype                                         prototype




                                Protótipo
                                do Date()


                    ECMAScript Language Specification
                      5th edition (December 2009)
“        Furthermore, a prototype may have a
           non-null implicit reference to its
        prototype, and so on; this is called the
                prototype chain.

    Date()
    <<construtor




                           Protótipo
                           do Date()


                   ECMAScript Language Specification
                     5th edition (December 2009)
“        Furthermore, a prototype may have a
           non-null implicit reference to its
        prototype, and so on; this is called the
                prototype chain.

    Date()
    <<construtor                           Protótipo do
                                           protótipo do
                                              Date()




                                                          Protótipo do
                           Protótipo                      protótipo do
                           do Date()                      protótipo do
                                                             Date()



                   ECMAScript Language Specification
                     5th edition (December 2009)
“   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)
“       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.


  obj
                              p3:
p1: “um”                     “tres”




                 p2:                         p4:
                “dois”                     “quatro”




                 ECMAScript Language Specification
                   5th edition (December 2009)
“       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.


  obj                                                 obj.p1
                              p3:
p1: “um”                     “tres”




                 p2:                         p4:
                “dois”                     “quatro”




                 ECMAScript Language Specification
                   5th edition (December 2009)
“       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.


  obj                                                 obj.p1
                              p3:
p1: “um”                     “tres”                   obj.p2


                 p2:                         p4:
                “dois”                     “quatro”




                 ECMAScript Language Specification
                   5th edition (December 2009)
“       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.


  obj                                                 obj.p1
                              p3:
p1: “um”                     “tres”                   obj.p2
                                                      obj.p3
                 p2:                         p4:
                “dois”                     “quatro”




                 ECMAScript Language Specification
                   5th edition (December 2009)
“       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.


  obj                                                 obj.p1
                              p3:
p1: “um”                     “tres”                   obj.p2
                                                      obj.p3
                 p2:                         p4:
                                                      obj.p4
                “dois”                     “quatro”




                 ECMAScript Language Specification
                   5th edition (December 2009)
> var Pessoa = function(nome, idade) {
    this.nome = nome;
    this.idade = idade;
  }


> var alexandre = new Pessoa('Ale', 33);
> alexandre.nome
"Ale"
> alexandre.idade
33


> var sebastiana = new Pessoa('Sebastiana', 88);
> sebastiana.nome
"Sebastiana"
> sebastiana.idade
88
> var Pessoa = function(nome, idade) {
    this.nome = nome;
    this.idade = idade;
  }                            construtor


> var alexandre = new Pessoa('Ale', 33);
> alexandre.nome
"Ale"
> alexandre.idade
33


> var sebastiana = new Pessoa('Sebastiana', 88);
> sebastiana.nome
"Sebastiana"
> sebastiana.idade
88
> var Pessoa = function(nome, idade) {
    this.nome = nome;
    this.idade = idade;
  }


> var alexandre = new Pessoa('Ale', 33);
> alexandre.nome
"Ale"
> alexandre.idade
33                                objeto 1


> var sebastiana = new Pessoa('Sebastiana', 88);
> sebastiana.nome
"Sebastiana"
> sebastiana.idade
88
> var Pessoa = function(nome, idade) {
    this.nome = nome;
    this.idade = idade;
  }


> var alexandre = new Pessoa('Ale', 33);
> alexandre.nome
"Ale"
> alexandre.idade
33


> var sebastiana = new Pessoa('Sebastiana', 88);
> sebastiana.nome
"Sebastiana"
> sebastiana.idade
88                                       objeto 2
Pessoa()
<<construtor>

   nome
   idade
Protótipo do
   Pessoa()




Pessoa()
<<construtor>

   nome
   idade
Protótipo do
                  Pessoa()




               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do
                  Pessoa()

                                                                ?
                                                 > alexandre.nome




               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do                     > alexandre.nome
                  Pessoa()
                                                 “Ale”




               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do                     > alexandre.nome
                  Pessoa()
                                                 “Ale”

                                                 > sebastiana.idade
                                                 88

               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do                     > alexandre.nome
                  Pessoa()
                                                 “Ale”

                                                 > sebastiana.idade
                                                 88

               Pessoa()


                                                                 ?
               <<construtor>
                                                 > alexandre.sexo
                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do                     > alexandre.nome
                  Pessoa()
                                                 “Ale”

                                                 > sebastiana.idade
                                                 88

               Pessoa()
               <<construtor>
                                                 > alexandre.sexo
                  nome
                                                 undefined
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo do                     > alexandre.nome
                  Pessoa()
                                                 “Ale”

                                                 > sebastiana.idade
                                                 88

               Pessoa()
               <<construtor>
                                                 > alexandre.sexo
                  nome
                                                 undefined
                  idade
                                                 > sebastiana.sexo
                                                 undefined

alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo




               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo           > Pessoa.prototype.sexo = “M”

                  sexo



               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo           > Pessoa.prototype.sexo = “M”

                  sexo                            > alexandre.sexo
                                                              “M”



               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo           > Pessoa.prototype.sexo = “M”

                  sexo                            > alexandre.sexo
                                                              “M”
                                                 > sebastiana.sexo
                                                              “M”
               Pessoa()
               <<construtor>

                  nome
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo           > Pessoa.prototype.sexo = “M”

                  sexo                                  > alexandre.sexo
                                                                    “M”
                                                       > sebastiana.sexo
                                                                    “M”
               Pessoa()
               <<construtor>

                  nome                           > sebastiana.sexo = “F”
                  idade




alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Protótipo           > Pessoa.prototype.sexo = “M”

                  sexo                                  > alexandre.sexo
                                                                    “M”
                                                       > sebastiana.sexo
                                                                    “M”
               Pessoa()
               <<construtor>

                  nome                           > sebastiana.sexo = “F”
                  idade
                                                       > sebastiana.sexo
                                                                    “F”


alexandre                       sebastiana

nome = ‘Ale’                   nome = ‘Seb...’
 idade = 33                      idade = 88
Object
Object   Prototipo de Object
Object    Prototipo de Object




Object.prototype.pO = 1
Object    Prototipo de Object

                pO = 1




Object.prototype.pO = 1
Object      Prototipo de Object

                 pO = 1



  A

 a=2


var A = function() {
  this.a = 2;
}
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2
Object    Prototipo de Object

               pO = 1



  A        Prototipo de A

 a=2           pA = 3




A.prototype.pA = 3
Object        Prototipo de Object

                   pO = 1



  A            Prototipo de A

 a=2               pA = 3



  B      var B = function() {
           this.b = 4;
b=4
         }
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3



  B       Prototipo de B

b=4
Object        Prototipo de Object

      B.prototype = new A
                pO = 1



  A            Prototipo de A

 a=2               pA = 3



  B            Prototipo de B

b=4
Object        Prototipo de Object

      B.prototype = new A
                pO = 1



  A            Prototipo de A

 a=2               pA = 3



  B
                   new A()
b=4
Object       Prototipo de Object

      B.prototype.pB = 5
                pO = 1



  A           Prototipo de A

 a=2              pA = 3



  B
                  new A()
b=4
                  pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3



  B
              new A()
b=4
              pB = 5
Object       Prototipo de Object

         x = new= 1
               pO
                  B()

  A           Prototipo de A

 a=2              pA = 3



  B
                  new A()          X
b=4
                  pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3



  B
              new A()          X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.pB
                                    ?
  B
              new A()           X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.b

  B
              new A()           X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.b
                                     ?
  B
              new A()           X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.pA

  B
              new A()            X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.pA
                                     ?
  B
              new A()            X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.a

  B
              new A()           X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.a
                                     ?
  B
              new A()           X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.pO

  B
              new A()            X
b=4
              pB = 5
Object   Prototipo de Object

              pO = 1



  A       Prototipo de A

 a=2          pA = 3
                               x.pO
                                     ?
  B
              new A()            X
b=4
              pB = 5
@see
        http://www.w3schools.com/js/default.asp

  https://developer.mozilla.org/en/JavaScript/Reference

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/
http://plugins.jquery.com/

•   Ajax
                               •   Layout
•   Animation and Effects
                               •   Media
•   Browser Tweaks
                               •   Menus
•   Data
                               •   Metaplugin
•   DOM
                               •   Navigation
•   Drag-and-Drop
                               •   Tables
•   Events
                               •   User Interface
•   Forms
                               •   Utilities
•   Integration
                               •   Widgets
•   JavaScript
                               •   Windows and Overlays
•   jQuery Extensions
http://www.prototypejs.org/
http://script.aculo.us/
http://madrobby.github.com/scriptaculous/combination-effects-demo/
http://raphaeljs.com/
Node's goal is to provide an
easy way to build scalable
   network programs.


        http://nodejs.org/
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.


      http://documentcloud.github.com/backbone/
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)
P&R
Javascript do jeito certo

Contenu connexe

Tendances

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...yaevents
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoPaulo Morgado
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersRick Beerendonk
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Sungchul Park
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
What's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOutWhat's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOutPaulo Morgado
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScriptnodejsbcn
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Sumant Tambe
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NETDoommaker
 

Tendances (19)

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신Beyond Java: 자바 8을 중심으로 본 자바의 혁신
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
 
Day 1
Day 1Day 1
Day 1
 
C# Today and Tomorrow
C# Today and TomorrowC# Today and Tomorrow
C# Today and Tomorrow
 
Java Performance MythBusters
Java Performance MythBustersJava Performance MythBusters
Java Performance MythBusters
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
What's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOutWhat's New In C# 5.0 - Rumos InsideOut
What's New In C# 5.0 - Rumos InsideOut
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
The Joy Of Ruby
The Joy Of RubyThe Joy Of Ruby
The Joy Of Ruby
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Managed Compiler
Managed CompilerManaged Compiler
Managed Compiler
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
 

En vedette

Javascript orientado a testes
Javascript orientado a testesJavascript orientado a testes
Javascript orientado a testesAlexandre Gomes
 
Programação Funcional com Javascript
Programação Funcional com JavascriptProgramação Funcional com Javascript
Programação Funcional com JavascriptAlexandre Gomes
 
Construção de Software - 1º/2016
Construção de Software - 1º/2016Construção de Software - 1º/2016
Construção de Software - 1º/2016Alexandre Gomes
 
OpenData, Web Semântica e afins.
OpenData, Web Semântica e afins.OpenData, Web Semântica e afins.
OpenData, Web Semântica e afins.Alexandre Gomes
 

En vedette (8)

Aprendendo a Aprender
Aprendendo a AprenderAprendendo a Aprender
Aprendendo a Aprender
 
Javascript orientado a testes
Javascript orientado a testesJavascript orientado a testes
Javascript orientado a testes
 
Programação Funcional com Javascript
Programação Funcional com JavascriptProgramação Funcional com Javascript
Programação Funcional com Javascript
 
Business Modeling
Business ModelingBusiness Modeling
Business Modeling
 
O Pensamento Ágil
O Pensamento ÁgilO Pensamento Ágil
O Pensamento Ágil
 
Computacao Invisivel
Computacao InvisivelComputacao Invisivel
Computacao Invisivel
 
Construção de Software - 1º/2016
Construção de Software - 1º/2016Construção de Software - 1º/2016
Construção de Software - 1º/2016
 
OpenData, Web Semântica e afins.
OpenData, Web Semântica e afins.OpenData, Web Semântica e afins.
OpenData, Web Semântica e afins.
 

Similaire à Javascript do jeito certo

Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8Rafael Casuso Romate
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talkdesistartups
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 ReviewSperasoft
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development toolsSimon Kim
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Miłosz Sobczak
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsFin Chen
 

Similaire à Javascript do jeito certo (20)

Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
ECMA Script
ECMA ScriptECMA Script
ECMA Script
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()Ecmascript 2015 – best of new features()
Ecmascript 2015 – best of new features()
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 

Plus de Alexandre Gomes

Construção de Software - 1º/2017
Construção de Software - 1º/2017Construção de Software - 1º/2017
Construção de Software - 1º/2017Alexandre Gomes
 
UnB/PPCA/CS2016 - Projeto 2
UnB/PPCA/CS2016 - Projeto 2UnB/PPCA/CS2016 - Projeto 2
UnB/PPCA/CS2016 - Projeto 2Alexandre Gomes
 
Plano de Ensino de Tópicos Avançados em Engenharia de Software
Plano de Ensino de Tópicos Avançados em Engenharia de SoftwarePlano de Ensino de Tópicos Avançados em Engenharia de Software
Plano de Ensino de Tópicos Avançados em Engenharia de SoftwareAlexandre Gomes
 
Construção de Software - 1º semestre de 2014
Construção de Software - 1º semestre de 2014Construção de Software - 1º semestre de 2014
Construção de Software - 1º semestre de 2014Alexandre Gomes
 
Laboratório de Métodos Ágeis 1/2014 - Apresentação
Laboratório de Métodos Ágeis 1/2014 - ApresentaçãoLaboratório de Métodos Ágeis 1/2014 - Apresentação
Laboratório de Métodos Ágeis 1/2014 - ApresentaçãoAlexandre Gomes
 
Manifesto 2.0 para a Engenharia de Software
Manifesto 2.0 para a Engenharia de SoftwareManifesto 2.0 para a Engenharia de Software
Manifesto 2.0 para a Engenharia de SoftwareAlexandre Gomes
 
Arquiteturas Orientadas a Serviços com a JBoss SOA Platform
Arquiteturas Orientadas a Serviços com a JBoss SOA PlatformArquiteturas Orientadas a Serviços com a JBoss SOA Platform
Arquiteturas Orientadas a Serviços com a JBoss SOA PlatformAlexandre Gomes
 

Plus de Alexandre Gomes (16)

Construção de Software - 1º/2017
Construção de Software - 1º/2017Construção de Software - 1º/2017
Construção de Software - 1º/2017
 
TDDing com Javascript
TDDing com JavascriptTDDing com Javascript
TDDing com Javascript
 
UnB/PPCA/CS2016 - Projeto 2
UnB/PPCA/CS2016 - Projeto 2UnB/PPCA/CS2016 - Projeto 2
UnB/PPCA/CS2016 - Projeto 2
 
Plano de Ensino de Tópicos Avançados em Engenharia de Software
Plano de Ensino de Tópicos Avançados em Engenharia de SoftwarePlano de Ensino de Tópicos Avançados em Engenharia de Software
Plano de Ensino de Tópicos Avançados em Engenharia de Software
 
Manifesto 2.0
Manifesto 2.0Manifesto 2.0
Manifesto 2.0
 
Construção de Software - 1º semestre de 2014
Construção de Software - 1º semestre de 2014Construção de Software - 1º semestre de 2014
Construção de Software - 1º semestre de 2014
 
Design Thinking
Design ThinkingDesign Thinking
Design Thinking
 
Manifesto Ágil
Manifesto ÁgilManifesto Ágil
Manifesto Ágil
 
Laboratório de Métodos Ágeis 1/2014 - Apresentação
Laboratório de Métodos Ágeis 1/2014 - ApresentaçãoLaboratório de Métodos Ágeis 1/2014 - Apresentação
Laboratório de Métodos Ágeis 1/2014 - Apresentação
 
Scraping by examples
Scraping by examplesScraping by examples
Scraping by examples
 
Scraping by examples
Scraping by examplesScraping by examples
Scraping by examples
 
Escolhas 2.0
Escolhas 2.0Escolhas 2.0
Escolhas 2.0
 
Manifesto 2.0 para a Engenharia de Software
Manifesto 2.0 para a Engenharia de SoftwareManifesto 2.0 para a Engenharia de Software
Manifesto 2.0 para a Engenharia de Software
 
Struts 2.x
Struts 2.xStruts 2.x
Struts 2.x
 
Arquiteturas Orientadas a Serviços com a JBoss SOA Platform
Arquiteturas Orientadas a Serviços com a JBoss SOA PlatformArquiteturas Orientadas a Serviços com a JBoss SOA Platform
Arquiteturas Orientadas a Serviços com a JBoss SOA Platform
 
Computacao Invisivel
Computacao InvisivelComputacao Invisivel
Computacao Invisivel
 

Dernier

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Dernier (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Javascript do jeito certo

  • 1. Javascript do jeito certo Alexandre Gomes
  • 2. javascript ? a que te remete o termo
  • 3. <form> <input type=button value="Close Window" onClick="javascript:window.close();"> </form>
  • 4. <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>
  • 5. function validateForm() { var x = document.forms["myForm"]["fname"].value if (x == null || x == "") { alert("Nome obrigatório!"); return false; } }
  • 6. para a grande maioria, javascript = magia negra
  • 7.
  • 8.
  • 9.
  • 11.
  • 12.
  • 15. javascript Afinal, é do mal ou do bem?
  • 17. ISO IEC 16262 http://www.ecma-international.org/publications/standards/Ecma-262.htm
  • 18. ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. ECMAScript Language Specification 5th edition (December 2009)
  • 19. 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 5th edition (December 2009)
  • 20. 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 5th edition (December 2009)
  • 21. Some of the facilities of ECMAScript are similar to those used in other programming languages; in particular Java TM, Self, and Scheme ECMAScript Language Specification 5th edition (December 2009)
  • 22. 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 5th edition (December 2009)
  • 23. 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 5th edition (December 2009)
  • 24. 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 5th edition (December 2009)
  • 25. 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 5th edition (December 2009)
  • 26. Each Web browser and server that supports ECMAScript supplies its own host environment, completing the ECMAScript execution environment. ECMAScript Language Specification 5th edition (December 2009)
  • 27. ECMAScript is an object-oriented programming language (...) ECMAScript Language Specification 5th edition (December 2009)
  • 28. ECMAScript is an object-oriented programming language (...) Tipos Boolean, Number, String, Array, RegExp Operadores + - * / >> << >>> < > <= >= | & *= ^ ++ Comentários // /* */ Estruturas do while for if else try catch switch ECMAScript Language Specification 5th edition (December 2009)
  • 29. Tipos (construtores) Boolean Object Number Function String RegExp Array Date
  • 30. Tipos undefined var x; alert(x); ECMAScript Language Specification 5th edition (December 2009)
  • 31. Tipos null var x = null; alert(x); ECMAScript Language Specification 5th edition (December 2009)
  • 32. Tipos Boolean var x = true; if(x) { alert('Verdadeiro'); } Obs: 0 e null equivalem a false ECMAScript Language Specification 5th edition (December 2009)
  • 33. Tipos Number var x = 10; var y = 15; alert(x+y); var x = 10.1; var y = 15.2; alert(x+y); ECMAScript Language Specification 5th edition (December 2009)
  • 34. Tipos String var x = “Alexandre”; alert(x); ECMAScript Language Specification 5th edition (December 2009)
  • 35. Tipos Function var x = function() { alert("Alexandre"); }; x(); ECMAScript Language Specification 5th edition (December 2009)
  • 36. > 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()
  • 37. var x = new Boolean(true); if(x) { alert('Verdadeiro'); } var x = new String(“Alexandre”); alert(x); var x = new Number(10); var y = new Number(15); alert(x+y);
  • 38. Operadores / <<= ? : delete % >>= = void >> == *= typeof << != /= ++ >>> === %= -- < !== += + > & -= - <= ^ >>>= ~ >= | &= ! instanceof && ˆ= * || in |=
  • 39. Operadores delete var a = 1 undefined a 1 delete a true a ReferenceError: a is not defined ECMAScript Language Specification 5th edition (December 2009)
  • 40. Operadores typeof typeof 1 "number" typeof true "boolean" typeof "Alexandre" "string" typeof function() { alert('Oi') } "function" typeof null "object" ECMAScript Language Specification 5th edition (December 2009)
  • 41. Operadores ++ e -- var a = 1 undefined a++ 1 a 2 ++a 3 ECMAScript Language Specification 5th edition (December 2009)
  • 42. Operadores instanceof var a = "alexandre" undefined a instanceof String false var a = new String("alexandre") undefined a instanceof String true a instanceof Object true ECMAScript Language Specification 5th edition (December 2009)
  • 43. Operadores ==, !=, ===, !== 3 == "3" true 3 === "3" false 2 != "2" false 2 !== "2" true ECMAScript Language Specification 5th edition (December 2009)
  • 44. Estruturas if/else continue switch do/while break throw while return try/catch for with debugger for/in
  • 45. Estruturas if/else var a = true if (a) { alert('Verdadeiro') } else { alert('Falso') } ECMAScript Language Specification 5th edition (December 2009)
  • 46. Estruturas do/while var i = 1 do { alert(i); (...) i++; } while (i < 5) ECMAScript Language Specification 5th edition (December 2009)
  • 47. Estruturas for for ( var i = 1; i < 5; i++) { alert(i); } (...) ECMAScript Language Specification 5th edition (December 2009)
  • 48. Estruturas for/in var array = [1,3,5,7,9] for (var i in array) { alert(array[i]) } (...) ECMAScript Language Specification 5th edition (December 2009)
  • 49. Estruturas for/each/in > 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 } ECMAScript Language Specification 5th edition (December 2009)
  • 50. Estruturas with 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 } ECMAScript Language Specification 5th edition (December 2009)
  • 51. Estruturas switch/case var a = "alexandre"; switch (a) { case "sebastiao": alert("Tião?"); break; case "raimunda": alert("Raimundinha?"); break; case "alexandre": alert("Alê!"); break; } ECMAScript Language Specification 5th edition (December 2009)
  • 52. 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)
  • 53. Numa aplicação Javascript, coexistirão 3 grupos de objetos objetos definidos pela objetos definidos pelo objetos definidos pelo especificação web browser desenvolvedor ECMAScript Boolean window alexandre Number document mensagem String XMLHttpRequest ... Array ... ...
  • 54. An ECMAScript object is a collection of properties each with zero or more attributes that determine how each property can be used alexandre nome: “Alexandre” sobrenome: “Gomes” idade: 34 ECMAScript Language Specification 5th edition (December 2009)
  • 55. An ECMAScript object is a collection of properties each with zero or more attributes that determine how each property can be used alexandre nome: “Alexandre” sobrenome: “Gomes” idade: 34 modificável: false ECMAScript Language Specification 5th edition (December 2009)
  • 56. > 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)
  • 57. Properties are containers (slots) that hold other objects, primitive values, or functions. alexandre nome: “Alexandre” nascimento: new Date(1977,8,8,0,0,0,0) idade: function() { ... } ECMAScript Language Specification 5th edition (December 2009)
  • 58. 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)
  • 59. > var x = "Alexandre"; > x.length String 9 > 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>"
  • 60. Boolean >>> var x = true; >>> if(x) { alert('yes'); } else { alert('no') } // yes >>> !x false >>> x & false 0 >>> x && false false >>> x | false 1 >>> x || false true >>> var x = false; >>> if(x) { alert('yes'); } else { alert('no') } // no
  • 61. Number >>> var x = 10 >>> var y = 15; >>> z = x + y 25 >>> z.toFixed(2); "25.00" >>> z.toExponential(2); "2.50e+1" >>> 2.toExponential(2); SyntaxError: identifier starts immediately after numeric literal
  • 62. Math >>> Math.PI 3.141592653589793 >>> Math.sqrt(81); 9 >>> Math.tan(45); 1.6197751905438615 >>> Math.pow(3,2); 9 >>> Math.random(); 0.8528815588353642 >>> Math.random(); 0.955940929887219
  • 63. >>> var x = new Date(); 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)"
  • 64. >>> var x = new Date(); >>> x.toString(); Date "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)"
  • 65. >>> var texto = "O gato roeu a roupa do rei de roma"; >>> var regex = new RegExp("gato", “”); >>> texto.match(regex); ["gato"] Regex >>> 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"]
  • 66. >>> var obj = { "nome": "Alexandre", "idade" : "33" } >>> obj.constructor; Object() JSON >>> 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"
  • 67. var x = new Array(); >>> [] 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
  • 68. A web browser provides an ECMAScript host environment (...)
  • 69. > 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>, …
  • 70.
  • 71.
  • 72.
  • 73.
  • 74. { { Gecko Webkit
  • 75.
  • 76.
  • 77. e agora, prendam a respiração...
  • 78. apesar de ser OO, ECMAScript does not use classes such as those in C+ +, Smalltalk, or Java. ECMAScript Language Specification 5th edition (December 2009)
  • 79. “Classful” “Classless” reuso por herança de reuso por clonagem classes de objetos Pessoa joao nome nome: “João” sexo idade: 28 <<herda>> <<clona>> Funcionári maria o salário nome: “Maria” idade: 20
  • 80. “Classful” “Classless” modelagem modelagem top-down bottom-up primeiro a taxonomia e primeiro o seus relacionamentos... comportamento...
  • 81. “Classful” “Classless” objetos criados a objetos criados a partir de classes partir de clonagem... hoje = new Date() hoje = new Date() ...ou por ‘geração expontânea’ var x = { one: 1, two: 2 }
  • 82. “Classful” “Classless” objetos carregam a objetos carregam as estrutura e o características de comportamento de sua classe seu protótipo
  • 83. Programação baseada em protótipos protótipo
  • 84. Programação baseada em protótipos protótipo clone
  • 85. Programação baseada em protótipos protótipo clone
  • 86. Programação baseada em protótipos >>> var conta = { saldo: 1000.00 }; >>> conta.saldo 1000 >>> conta.limite undefined >>> var conta_especial = { limite: 500.00 } >>> conta_especial.limite 500 >>> conta_especial.saldo undefined >>> conta_especial.__proto__ = conta // referência explícita Object { saldo=1000} >>> conta_especial.saldo 1000
  • 87. 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()
  • 88. objects may be created in various ways including via a literal notation var conta = { saldo: 1000.00 } ECMAScript Language Specification 5th edition (December 2009)
  • 89. objects may be created in various ways including via a literal notation var conta = { saldo: 1000.00 } or via constructors hoje = new Date() ECMAScript Language Specification 5th edition (December 2009)
  • 90. Each constructor is a function hoje = new Date() function Date() { ... } ECMAScript Language Specification 5th edition (December 2009)
  • 91. mas function é também um objeto Date() var Date = function() { ... } hoje = new Date()
  • 92. construtor function Date() objeto
  • 93. construtor function Date() objeto propriedades
  • 94. “ 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)
  • 95. Each constructor is a function that has a property named “prototype”(...) Date() <<construtor prototype Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 96. Date() <<construtor prototype Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 97. Every object created by a constructor Date() <<construtor hoje = new Date() hoje prototype Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 98. Every object created by a constructor has an implicit reference (called the object’s prototype) Date() <<construtor hoje = new Date() hoje prototype prototype Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 99. Every object created by a constructor has an implicit reference (called the object’s prototype) to the value of its constructor’s “prototype” property. Date() <<construtor hoje = new Date() hoje prototype prototype Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 100. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. Date() <<construtor Protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 101. Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain. Date() <<construtor Protótipo do protótipo do Date() Protótipo do Protótipo protótipo do do Date() protótipo do Date() ECMAScript Language Specification 5th edition (December 2009)
  • 102. 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)
  • 103. 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. obj p3: p1: “um” “tres” p2: p4: “dois” “quatro” ECMAScript Language Specification 5th edition (December 2009)
  • 104. 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. obj obj.p1 p3: p1: “um” “tres” p2: p4: “dois” “quatro” ECMAScript Language Specification 5th edition (December 2009)
  • 105. 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. obj obj.p1 p3: p1: “um” “tres” obj.p2 p2: p4: “dois” “quatro” ECMAScript Language Specification 5th edition (December 2009)
  • 106. 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. obj obj.p1 p3: p1: “um” “tres” obj.p2 obj.p3 p2: p4: “dois” “quatro” ECMAScript Language Specification 5th edition (December 2009)
  • 107. 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. obj obj.p1 p3: p1: “um” “tres” obj.p2 obj.p3 p2: p4: obj.p4 “dois” “quatro” ECMAScript Language Specification 5th edition (December 2009)
  • 108. > var Pessoa = function(nome, idade) { this.nome = nome; this.idade = idade; } > var alexandre = new Pessoa('Ale', 33); > alexandre.nome "Ale" > alexandre.idade 33 > var sebastiana = new Pessoa('Sebastiana', 88); > sebastiana.nome "Sebastiana" > sebastiana.idade 88
  • 109. > var Pessoa = function(nome, idade) { this.nome = nome; this.idade = idade; } construtor > var alexandre = new Pessoa('Ale', 33); > alexandre.nome "Ale" > alexandre.idade 33 > var sebastiana = new Pessoa('Sebastiana', 88); > sebastiana.nome "Sebastiana" > sebastiana.idade 88
  • 110. > var Pessoa = function(nome, idade) { this.nome = nome; this.idade = idade; } > var alexandre = new Pessoa('Ale', 33); > alexandre.nome "Ale" > alexandre.idade 33 objeto 1 > var sebastiana = new Pessoa('Sebastiana', 88); > sebastiana.nome "Sebastiana" > sebastiana.idade 88
  • 111. > var Pessoa = function(nome, idade) { this.nome = nome; this.idade = idade; } > var alexandre = new Pessoa('Ale', 33); > alexandre.nome "Ale" > alexandre.idade 33 > var sebastiana = new Pessoa('Sebastiana', 88); > sebastiana.nome "Sebastiana" > sebastiana.idade 88 objeto 2
  • 112. Pessoa() <<construtor> nome idade
  • 113. Protótipo do Pessoa() Pessoa() <<construtor> nome idade
  • 114. Protótipo do Pessoa() Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 115. Protótipo do Pessoa() ? > alexandre.nome Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 116. Protótipo do > alexandre.nome Pessoa() “Ale” Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 117. Protótipo do > alexandre.nome Pessoa() “Ale” > sebastiana.idade 88 Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 118. Protótipo do > alexandre.nome Pessoa() “Ale” > sebastiana.idade 88 Pessoa() ? <<construtor> > alexandre.sexo nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 119. Protótipo do > alexandre.nome Pessoa() “Ale” > sebastiana.idade 88 Pessoa() <<construtor> > alexandre.sexo nome undefined idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 120. Protótipo do > alexandre.nome Pessoa() “Ale” > sebastiana.idade 88 Pessoa() <<construtor> > alexandre.sexo nome undefined idade > sebastiana.sexo undefined alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 121. Protótipo Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 122. Protótipo > Pessoa.prototype.sexo = “M” sexo Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 123. Protótipo > Pessoa.prototype.sexo = “M” sexo > alexandre.sexo “M” Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 124. Protótipo > Pessoa.prototype.sexo = “M” sexo > alexandre.sexo “M” > sebastiana.sexo “M” Pessoa() <<construtor> nome idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 125. Protótipo > Pessoa.prototype.sexo = “M” sexo > alexandre.sexo “M” > sebastiana.sexo “M” Pessoa() <<construtor> nome > sebastiana.sexo = “F” idade alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 126. Protótipo > Pessoa.prototype.sexo = “M” sexo > alexandre.sexo “M” > sebastiana.sexo “M” Pessoa() <<construtor> nome > sebastiana.sexo = “F” idade > sebastiana.sexo “F” alexandre sebastiana nome = ‘Ale’ nome = ‘Seb...’ idade = 33 idade = 88
  • 127. Object
  • 128. Object Prototipo de Object
  • 129. Object Prototipo de Object Object.prototype.pO = 1
  • 130. Object Prototipo de Object pO = 1 Object.prototype.pO = 1
  • 131. Object Prototipo de Object pO = 1 A a=2 var A = function() { this.a = 2; }
  • 132. Object Prototipo de Object pO = 1 A Prototipo de A a=2
  • 133. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 A.prototype.pA = 3
  • 134. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 B var B = function() { this.b = 4; b=4 }
  • 135. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 B Prototipo de B b=4
  • 136. Object Prototipo de Object B.prototype = new A pO = 1 A Prototipo de A a=2 pA = 3 B Prototipo de B b=4
  • 137. Object Prototipo de Object B.prototype = new A pO = 1 A Prototipo de A a=2 pA = 3 B new A() b=4
  • 138. Object Prototipo de Object B.prototype.pB = 5 pO = 1 A Prototipo de A a=2 pA = 3 B new A() b=4 pB = 5
  • 139. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 B new A() b=4 pB = 5
  • 140. Object Prototipo de Object x = new= 1 pO B() A Prototipo de A a=2 pA = 3 B new A() X b=4 pB = 5
  • 141. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 B new A() X b=4 pB = 5
  • 142. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.pB ? B new A() X b=4 pB = 5
  • 143. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.b B new A() X b=4 pB = 5
  • 144. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.b ? B new A() X b=4 pB = 5
  • 145. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.pA B new A() X b=4 pB = 5
  • 146. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.pA ? B new A() X b=4 pB = 5
  • 147. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.a B new A() X b=4 pB = 5
  • 148. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.a ? B new A() X b=4 pB = 5
  • 149. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.pO B new A() X b=4 pB = 5
  • 150. Object Prototipo de Object pO = 1 A Prototipo de A a=2 pA = 3 x.pO ? B new A() X b=4 pB = 5
  • 151. @see http://www.w3schools.com/js/default.asp https://developer.mozilla.org/en/JavaScript/Reference https://developer.mozilla.org/en/Gecko_DOM_Reference http://developer.apple.com/library/safari/#documentation/ AppleApplications/Reference/WebKitDOMRef/index.html
  • 152. o que tem sido feito com javascript
  • 154.
  • 155.
  • 156.
  • 157. http://plugins.jquery.com/ • Ajax • Layout • Animation and Effects • Media • Browser Tweaks • Menus • Data • Metaplugin • DOM • Navigation • Drag-and-Drop • Tables • Events • User Interface • Forms • Utilities • Integration • Widgets • JavaScript • Windows and Overlays • jQuery Extensions
  • 162.
  • 163. Node's goal is to provide an easy way to build scalable network programs. http://nodejs.org/
  • 164.
  • 165.
  • 166.
  • 167.
  • 168. 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. http://documentcloud.github.com/backbone/
  • 169. 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/
  • 170. if (opposite) { number = -42; } number = -42 if opposite
  • 171. square = function(x) { return x * x; }; square = (x) -> x * x
  • 172. 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)
  • 173. P&R

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. Mas a&amp;#xED; chegou o Google e lan&amp;#xE7;ou sua ferramenta de webmail, em meio a um mercado aparentemente saturado.\n
  8. ...popularizou uma t&amp;#xE9;cnica\n
  9. E mudou a percep&amp;#xE7;&amp;#xE3;o que o mundo tinha da tecnologia.\n
  10. \n
  11. Javascript &amp;#xE9; 3&amp;#xAA; tecnologia com mais projetos no Github\n
  12. ...e &amp;#xE9; a tecnologia que tem a maior base de c&amp;#xF3;digo!\n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. At&amp;#xE9; mesmo diferentes vers&amp;#xF5;es de browser prov&amp;#xEA;em diferentes hosts environments.\n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \\\n
  50. \\\n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. O fato &amp;#xE9; que....\n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. \n
  121. \n
  122. \n
  123. \n
  124. \n
  125. \n
  126. \n
  127. \n
  128. \n
  129. \n
  130. \n
  131. \n
  132. \n
  133. \n
  134. \n
  135. \n
  136. \n
  137. \n
  138. \n
  139. \n
  140. \n
  141. \n
  142. \n
  143. \n
  144. \n
  145. \n
  146. \n
  147. \n
  148. \n
  149. \n
  150. \n
  151. \n
  152. \n
  153. \n
  154. \n
  155. \n
  156. \n
  157. \n
  158. \n
  159. \n
  160. \n
  161. \n
  162. \n
  163. \n
  164. \n
  165. \n
  166. \n
  167. \n
  168. \n
  169. \n
  170. \n
  171. \n
  172. \n
  173. \n
  174. \n
  175. \n
  176. \n
  177. \n
  178. \n
  179. \n
  180. \n
  181. \n
  182. \n
  183. \n
  184. \n
  185. \n
  186. \n
  187. \n
  188. \n
  189. \n
  190. \n
  191. \n
  192. \n
  193. \n
  194. \n
  195. \n
  196. \n
  197. \n
  198. \n
  199. \n
  200. \n
  201. \n
  202. \n
  203. \n
  204. \n
  205. \n
  206. \n
  207. \n
  208. TODO\n- Subclasse com chamada a A.call(this) no construtor\n