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

Javascript do jeito certo

  • 1.
    Javascript do jeito certo Alexandre Gomes
  • 2.
    javascript ? a que te remete o termo
  • 3.
    <form> <inputtype=button value="Close Window" onClick="javascript:window.close();"> </form>
  • 4.
    <script> functionopen_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 grandemaioria, javascript = magia negra
  • 10.
  • 13.
  • 14.
  • 15.
    javascript Afinal, é do mal ou do bem?
  • 16.
  • 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>, …
  • 74.
    { { Gecko Webkit
  • 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.
    “ Eachconstructor 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.
  • 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.
  • 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 temsido feito com javascript
  • 153.
  • 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
  • 158.
  • 159.
  • 160.
  • 161.
  • 163.
    Node's goal isto provide an easy way to build scalable network programs. http://nodejs.org/
  • 168.
    Backbone supplies structureto 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 alittle 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.

Editor's Notes