SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
AJAX и будущее JavaScript


        Константин Кичинский
                        kichinsky@mainfo.ru
             http://zelo-stroi.livejournal.com
JavaScript
AJAX |   Asynchronous
         JavaScript and XML
Ajax
• XMLHttpRequest + XML
Ajax
• XMLHttpRequest — API, предоставляемое
  браузером и доступное через JavaScript,
  позволяющее передавать XML и другие
  текстовые данные между клиентом и
  сервером посредством протокола HTTP
  путем установления независимых и
  асинхронных соединений между веб-
  страницей на клиенте и веб-сервером.
function ajax(url, vars, callbackFunction){

    var request = window.XMLHttpRequest ? new XMLHttpRequest() : new
    ActiveXObject(quot;MSXML2.XMLHTTP.3.0quot;);

    request.open(quot;POSTquot;, url, true);
    request.setRequestHeader(quot;Content-Typequot;, quot;application/x-www-form-urlencodedquot;);

    request.onreadystatechange = function(){

         if (request.readyState == 4 && request.status == 200) {

             if (request.responseText){


                                                                   ext);
                  callbackFunction(request.responseT
             }
         }
    }
    request.send(vars);
}
if( !window.XMLHttpRequest ) XMLHttpRequest = function(){
     try{
            return new ActiveXObject(quot;MSXML3.XMLHTTPquot;)
     } catch(e){}
     try{
            return new ActiveXObject(quot;MSXML2.XMLHTTP.3.0quot;)
      }catch(e){}
     try{
            return new ActiveXObject(quot;Msxml2.XMLHTTPquot;)
     }catch(e){}
     try{
            return new ActiveXObject(quot;Microsoft.XMLHTTPquot;)
      }catch(e){}
     throw new Error(quot;Could not find an XMLHttpRequest alternative.quot;)
};
• DOM — Document Object Model, способ
  представления html- или xml-документа в
  виде объектной модели, не зависящий от
  платформы и языка реализации.

• DOM описывает способы навигации по
  документу и методы доступа к значениям
  элементов и их атрибутам.
<?xml version=”1.0” ?>
  <files>
       <file author='Constantin'>
       <address>http://files.mainfo.ru/infa_labs1.zip</address>
       <description>Задания на лабораторную работу №1 по
         информатике</description>
       </file>
…
       <file author='Constantin'>
            <address>http://files.mainfo.ru/infa_labs10.zip</address>
            <description>Задания на лабораторную работу №10 по
              информатике</description>
       </file>
</files>
function parseFilesXMLDocument(filesXMLDoc) {
    var files =
      filesXMLDoc.getElementsByTagName('files').item(0);
    for (var iFile = 0; iFile < files.childNodes.length; iFile++) {
        var file = files.childNodes.item(iFile);
        file.author = file.getAttribute('author');
        file.address = file.getElementsByTagName(' address').item(0).data;
        file.description =
           file.getElementsByTagName('description').item(0).data;
        addFile(file);
    }
}
function addFile(file) {
  var fileHTML = ''<div class='file'>'' + ''<span
  class='description'>'' + file. description +
  ''</span'' + ''<span class='author'>'' +
  file.author + ''</span>'' + ''<span
  class='download'>'' + ''<a href=' '' +
  file.address + '''>скачать</a>'';
  …
}
• JSON — JavaScript Object Notation, простой
  формат обмена данными, удобный для
  чтения и написания как человеком, так и
  компьютером, основанный на
  подмножестве языка JavaScript.

• var jsObject = eval(' (' + jsonString + ') ');
{ files: [
     {
             author: 'Constantin',
             address: 'http://files.mainfo.ru/infa_labs1.zip',
             description: 'Задания на лабораторную работу №1 по информатике';
     },
     …
     {
             author: 'Constantin',
             address: 'http://files.mainfo.ru/infa_labs10.zip',
             description: 'Задания на лабораторную работу №10 по информатике';
     }
]
}
function parseFilesJSONDocument(filesJSONDoc)
  {
    var files = filesJSONDoc.parseJSON().files;
    for (var iFile = 0; iFile < files.length; iFile++) {
      addFile(files[iFile]);
    }
}
• E4X — ECMAScript for XML, расширение
  языков семества ECMASCript (включая
  JavaScript) для нативной (встроенной)
  поддержки работы с XML, позволяющей
  работать с XML документами, учитывая их
  семантику.
function parseFilesE4XDocument(filesE4XDoc) {
   for each (var file in filesE4XDoc.files) {
         addFile(file);
   }
}
function addFile(file) {
var fileHTML = ''<div class='file'>'' + ''<span class='description'>'' +
   file.description + ''</span'' + ''<span class='author'>'' + file.@author
   + ''</span>'' + ''<span class='download'>'' + ''<a href=' '' +
   file.address + '''>скачать</a>'';
…
}
• EX4 – начиная с JavaScript 1.7
• JSON – скоро непосредственно в JavaScript,
  сейчас – json.org
Каким он будет?
JavaScript 2 – ECMAScript 4

ООП
• ECMASript4 поддерживает объектно-
  ориентированное программирование
  введением таких структур, как классы (class)
  и интерфейсы (interface) — подобно языку
  Java.
JavaScript 2 – ECMAScript 4

ООП
• class C extends B {
      function C(m) {
        mem = m
      }
      public function getmem() {
             return mem
      }
      private var mem : Object
   }
   var c : C = new C(new Date)
JavaScript 2 – ECMAScript 4

ООП
• interface I {
       function meth(int) : int
   }

   class B implements I {
      public function meth(a : int) : int {
        return a * a
      }
    }
JavaScript 2 -- ECMAScript 4

Пакеты
• Модульность приложения поддерживается
  пакетами (package) и пространствами имен
  (namespace).
JavaScript 2 -- ECMAScript 4

namespace improved {
  class C {
      public function frob(): int {...}
      public improved function frob(alpha: double): double { ...
       }
  }
}
c.improved::frob(1.2)
use namespace improved . . . c.frob(alpha)
JavaScript 2 -- ECMAScript 4

package org.mozilla.venkman {
class Debugger { . . . }
class Inspector { . . . }
class StackWalker { . . . }
 }

import org.mozilla.venkman.
// use Debugger, Inspector, etc. freely
JavaScript 2 -- ECMAScript 4

Строгие типы данных
• Программирование больших проектов
  упрощается за счет введения строгих типов
  данных, определяемых классами и
  интерфейсами.
JavaScript 2 -- ECMAScript 4

Оптимизация времени и пространства
• Строгая типизация облегчает раннее
  связывание точек вызова и вызываемых из
  них методов, что потенциально уменьшает
  стоимость вызова методов по сравнению с
  ES3.
JavaScript 2 -- ECMAScript 4

Данные
• Параметризованные классы,
  Array[[T]] для Array типа T
• объекты с геттер и сеттер-методами,
• Типизация функций
  function f(a : int, b : String, c : Object) : RetType {
       // arguments are guaranteed to match types

      // return value must convert to or match RetType

  }
JavaScript 2 -- ECMAScript 4

•   Структурные типы
        type Q = {p: int, q: String}
         type R = {p: int, q: String, r: Boolean}
        type A = [int, String, Boolean, Object]

•   Функциональный тип данных
     type F = function (int, String, Boolean): Object
     type G = function (int, Object, Object): Number

        Объединения
        type U = (R, A, F)

•   function f(a : int, b : String, ...rest) {
             // rest is of type Array, contains actual trailing arguments
    }
JavaScript 2 -- ECMAScript 4

• Групповые присваивания
   // swap, rotate, permute in general
   [a, b] = [b, a]
   [p, q, r] = [q, r, p]
• // destructure a triple into fresh vars
  var [s, v, o] = db.getTriple()
• let {'Title': title, 'Height': height, 'Width': width} =
  jsonResult
• for (let [key, {'Title':title, 'FileSize':size}] in dict)
  print(key, title, size)
JavaScript 2 -- ECMAScript 4
•   Итераторы
•   let it = Iterator([quot;meowquot;, quot;oinkquot;, quot;woofquot;])
•   it.next() returns [0, quot;meowquot;]
•   it.next() returns [1, quot;oinkquot;]
•   it.next() returns [2, quot;woofquot;]

• for (let i in it) print(i)
JavaScript 2 -- ECMAScript 4
• Генераторы
• function count(n : int) {
   for (let i = 0; i < n; i++)
       yield i
   }
• var gen = count(10)
• gen.next() returns 0; . . .; gen.next() returns 9
  gen.next() throws StopIteration
JavaScript 2 -- ECMAScript 4
• Заполнение массивов
• let squares = [i * i for (i in count(10))]
  print(squares) => quot;0,1,4,9,...,81«

• let odd_squares = [i * i for (i in count(10)) if (i
  % 2)]
• return [i * j for (i in it1) for (j in it2) if (i != j)]
JavaScript 2 -- ECMAScript 4
• Операторы
• class Complex {
  var real:Number, imag:Number;
  public static function +(a:Object, b:Object):Complex {
  if (a is Complex && b is Complex)
     return new Complex(a.real + b.real, a.imag + b.imag)
  if (b == null) return (a is Complex) ? a : new Complex(a)
     return intrinsic::+(a, b) } . . . }
0.1 + 0.2 === 0.3,
а не 0.30000000000000004
• http://www.ecmascript.org/es4/spec/overvie
  w.pdf

Más contenido relacionado

La actualidad más candente

Type the document source
Type the document sourceType the document source
Type the document sourceMark Hilbert
 
Nginx常见应用技术指南(Nginx Tips)
Nginx常见应用技术指南(Nginx Tips)Nginx常见应用技术指南(Nginx Tips)
Nginx常见应用技术指南(Nginx Tips)dreamwing.org
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web AppsMark
 
Reactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/OReactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/OArawn Park
 
Asynchonicity: concurrency. A tale of
Asynchonicity: concurrency. A tale ofAsynchonicity: concurrency. A tale of
Asynchonicity: concurrency. A tale ofJoel Lord
 
ZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionIan Barber
 
Scalable vector ember
Scalable vector emberScalable vector ember
Scalable vector emberMatthew Beale
 
Asynchronicity: concurrency. A tale of
Asynchronicity: concurrency. A tale ofAsynchronicity: concurrency. A tale of
Asynchronicity: concurrency. A tale ofJoel Lord
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror StoriesSimon Willison
 
Portafolio.carlos serrano grupo 201512_20
Portafolio.carlos serrano grupo 201512_20Portafolio.carlos serrano grupo 201512_20
Portafolio.carlos serrano grupo 201512_20carloser12
 
UAA for Kubernetes
UAA for KubernetesUAA for Kubernetes
UAA for KubernetesAltoros
 
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2016
 
GedcomX SDK - Getting Started
GedcomX SDK - Getting StartedGedcomX SDK - Getting Started
GedcomX SDK - Getting StartedDave Nash
 
Troubleshooting .NET Applications on Cloud Foundry
Troubleshooting .NET Applications on Cloud FoundryTroubleshooting .NET Applications on Cloud Foundry
Troubleshooting .NET Applications on Cloud FoundryAltoros
 
Going Schema-Free
Going Schema-FreeGoing Schema-Free
Going Schema-Freespraints
 
Token Based Authentication Systems
Token Based Authentication SystemsToken Based Authentication Systems
Token Based Authentication SystemsHüseyin BABAL
 
Social Analytics with MongoDB
Social Analytics with MongoDBSocial Analytics with MongoDB
Social Analytics with MongoDBPatrick Stokes
 

La actualidad más candente (20)

Type the document source
Type the document sourceType the document source
Type the document source
 
Cracking Salted Hashes
Cracking Salted HashesCracking Salted Hashes
Cracking Salted Hashes
 
Nginx常见应用技术指南(Nginx Tips)
Nginx常见应用技术指南(Nginx Tips)Nginx常见应用技术指南(Nginx Tips)
Nginx常见应用技术指南(Nginx Tips)
 
Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
Reactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/OReactive Web - Servlet & Async, Non-blocking I/O
Reactive Web - Servlet & Async, Non-blocking I/O
 
Asynchonicity: concurrency. A tale of
Asynchonicity: concurrency. A tale ofAsynchonicity: concurrency. A tale of
Asynchonicity: concurrency. A tale of
 
ZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 VersionZeroMQ Is The Answer: PHP Tek 11 Version
ZeroMQ Is The Answer: PHP Tek 11 Version
 
Scalable vector ember
Scalable vector emberScalable vector ember
Scalable vector ember
 
Asynchronicity: concurrency. A tale of
Asynchronicity: concurrency. A tale ofAsynchronicity: concurrency. A tale of
Asynchronicity: concurrency. A tale of
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
 
Portafolio.carlos serrano grupo 201512_20
Portafolio.carlos serrano grupo 201512_20Portafolio.carlos serrano grupo 201512_20
Portafolio.carlos serrano grupo 201512_20
 
UAA for Kubernetes
UAA for KubernetesUAA for Kubernetes
UAA for Kubernetes
 
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
festival ICT 2013: Solid as diamond: use ruby in an web application penetrati...
 
GedcomX SDK - Getting Started
GedcomX SDK - Getting StartedGedcomX SDK - Getting Started
GedcomX SDK - Getting Started
 
Troubleshooting .NET Applications on Cloud Foundry
Troubleshooting .NET Applications on Cloud FoundryTroubleshooting .NET Applications on Cloud Foundry
Troubleshooting .NET Applications on Cloud Foundry
 
Bash Scripting Workshop
Bash Scripting WorkshopBash Scripting Workshop
Bash Scripting Workshop
 
Going Schema-Free
Going Schema-FreeGoing Schema-Free
Going Schema-Free
 
Token Based Authentication Systems
Token Based Authentication SystemsToken Based Authentication Systems
Token Based Authentication Systems
 
Social Analytics with MongoDB
Social Analytics with MongoDBSocial Analytics with MongoDB
Social Analytics with MongoDB
 

Destacado

Vamos ler 7ºb e 9ºb
Vamos ler 7ºb e 9ºbVamos ler 7ºb e 9ºb
Vamos ler 7ºb e 9ºbbiblucena
 
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtia
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtiaTeosofisen liikkeen ja gnostilaisuuden yhtymäkohtia
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtiaTeosofinenSeura
 
Codes and conventions A2 MediaStudies
Codes and conventions A2 MediaStudiesCodes and conventions A2 MediaStudies
Codes and conventions A2 MediaStudiesCharlieOBarker
 
トーマツ「復興支援室の取り組み」
トーマツ「復興支援室の取り組み」トーマツ「復興支援室の取り組み」
トーマツ「復興支援室の取り組み」csr_alterna
 
6. Co to jest bezpieczeństwo żywnościowe?
6. Co to jest bezpieczeństwo żywnościowe? 6. Co to jest bezpieczeństwo żywnościowe?
6. Co to jest bezpieczeństwo żywnościowe? KlimatDlaRolnikow
 
L´Orient Saint Barth | Apartamentos de 4 suítes na Península
L´Orient Saint Barth | Apartamentos de 4 suítes na PenínsulaL´Orient Saint Barth | Apartamentos de 4 suítes na Península
L´Orient Saint Barth | Apartamentos de 4 suítes na PenínsulaLancamentosrj
 
Escuta5 ae5e
Escuta5 ae5eEscuta5 ae5e
Escuta5 ae5ebiblucena
 
Segurança cibernética: Desafios e oportunidades na era de ciberespionagem
Segurança cibernética: Desafios e oportunidades na era de ciberespionagemSegurança cibernética: Desafios e oportunidades na era de ciberespionagem
Segurança cibernética: Desafios e oportunidades na era de ciberespionagemMehran Misaghi
 
As novas tecnologias ao serviço dos alunos com nee
As novas tecnologias ao serviço dos alunos com neeAs novas tecnologias ao serviço dos alunos com nee
As novas tecnologias ao serviço dos alunos com neeunisalete34
 
Natal pode ser todos os dias
Natal pode ser todos os diasNatal pode ser todos os dias
Natal pode ser todos os diaselizabethrollas
 
Spanish 4 presentation
Spanish 4 presentationSpanish 4 presentation
Spanish 4 presentationdaadl001
 
Fraternitas maio 2012
Fraternitas maio 2012Fraternitas maio 2012
Fraternitas maio 2012scapolan
 
Taller 3 | pinterest, instagram, youtube, google+
Taller 3 | pinterest, instagram, youtube, google+Taller 3 | pinterest, instagram, youtube, google+
Taller 3 | pinterest, instagram, youtube, google+Diagonal M&P
 
English lesson
English lessonEnglish lesson
English lessonAna Ramos
 
Kit de supervivència pla d'acollida mestres
Kit de supervivència pla d'acollida mestresKit de supervivència pla d'acollida mestres
Kit de supervivència pla d'acollida mestresjpinyol2
 
AnáLisis Financiero De La Empresa
AnáLisis Financiero De La EmpresaAnáLisis Financiero De La Empresa
AnáLisis Financiero De La EmpresaPiedad1963
 

Destacado (20)

Vamos ler 7ºb e 9ºb
Vamos ler 7ºb e 9ºbVamos ler 7ºb e 9ºb
Vamos ler 7ºb e 9ºb
 
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtia
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtiaTeosofisen liikkeen ja gnostilaisuuden yhtymäkohtia
Teosofisen liikkeen ja gnostilaisuuden yhtymäkohtia
 
Codes and conventions A2 MediaStudies
Codes and conventions A2 MediaStudiesCodes and conventions A2 MediaStudies
Codes and conventions A2 MediaStudies
 
トーマツ「復興支援室の取り組み」
トーマツ「復興支援室の取り組み」トーマツ「復興支援室の取り組み」
トーマツ「復興支援室の取り組み」
 
6. Co to jest bezpieczeństwo żywnościowe?
6. Co to jest bezpieczeństwo żywnościowe? 6. Co to jest bezpieczeństwo żywnościowe?
6. Co to jest bezpieczeństwo żywnościowe?
 
Procesos
ProcesosProcesos
Procesos
 
Boletín Ocio Noviembre 2011 Enero 2012
Boletín Ocio Noviembre 2011 Enero 2012Boletín Ocio Noviembre 2011 Enero 2012
Boletín Ocio Noviembre 2011 Enero 2012
 
L´Orient Saint Barth | Apartamentos de 4 suítes na Península
L´Orient Saint Barth | Apartamentos de 4 suítes na PenínsulaL´Orient Saint Barth | Apartamentos de 4 suítes na Península
L´Orient Saint Barth | Apartamentos de 4 suítes na Península
 
Escuta5 ae5e
Escuta5 ae5eEscuta5 ae5e
Escuta5 ae5e
 
Segurança cibernética: Desafios e oportunidades na era de ciberespionagem
Segurança cibernética: Desafios e oportunidades na era de ciberespionagemSegurança cibernética: Desafios e oportunidades na era de ciberespionagem
Segurança cibernética: Desafios e oportunidades na era de ciberespionagem
 
As novas tecnologias ao serviço dos alunos com nee
As novas tecnologias ao serviço dos alunos com neeAs novas tecnologias ao serviço dos alunos com nee
As novas tecnologias ao serviço dos alunos com nee
 
Natal pode ser todos os dias
Natal pode ser todos os diasNatal pode ser todos os dias
Natal pode ser todos os dias
 
Boletín ocio Febrero- Abril 2013
Boletín ocio Febrero- Abril 2013 Boletín ocio Febrero- Abril 2013
Boletín ocio Febrero- Abril 2013
 
Spanish 4 presentation
Spanish 4 presentationSpanish 4 presentation
Spanish 4 presentation
 
Fraternitas maio 2012
Fraternitas maio 2012Fraternitas maio 2012
Fraternitas maio 2012
 
Bab i
Bab iBab i
Bab i
 
Taller 3 | pinterest, instagram, youtube, google+
Taller 3 | pinterest, instagram, youtube, google+Taller 3 | pinterest, instagram, youtube, google+
Taller 3 | pinterest, instagram, youtube, google+
 
English lesson
English lessonEnglish lesson
English lesson
 
Kit de supervivència pla d'acollida mestres
Kit de supervivència pla d'acollida mestresKit de supervivència pla d'acollida mestres
Kit de supervivència pla d'acollida mestres
 
AnáLisis Financiero De La Empresa
AnáLisis Financiero De La EmpresaAnáLisis Financiero De La Empresa
AnáLisis Financiero De La Empresa
 

Similar a Ajax и будущее Java Script

20070407 Rit2007 Xmltype Samokhvalov
20070407 Rit2007 Xmltype Samokhvalov20070407 Rit2007 Xmltype Samokhvalov
20070407 Rit2007 Xmltype SamokhvalovNikolay Samokhvalov
 
Devclub Servicemix Jevgeni Holodkov 23 04 09
Devclub Servicemix Jevgeni Holodkov 23 04 09Devclub Servicemix Jevgeni Holodkov 23 04 09
Devclub Servicemix Jevgeni Holodkov 23 04 09helggeist
 
The Real Time Web with XMPP
The Real Time Web with XMPPThe Real Time Web with XMPP
The Real Time Web with XMPPJack Moffitt
 
49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)Kritika910
 
톰캣 #05-배치
톰캣 #05-배치톰캣 #05-배치
톰캣 #05-배치GyuSeok Lee
 
JSARToolKit / LiveChromaKey / LivePointers - Next gen of AR
JSARToolKit / LiveChromaKey / LivePointers - Next gen of ARJSARToolKit / LiveChromaKey / LivePointers - Next gen of AR
JSARToolKit / LiveChromaKey / LivePointers - Next gen of ARYusuke Kawasaki
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shellady36
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkejElinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkejPertti Paavola
 
yusukebe in Yokohama.pm 090909
yusukebe in Yokohama.pm 090909yusukebe in Yokohama.pm 090909
yusukebe in Yokohama.pm 090909Yusuke Wada
 

Similar a Ajax и будущее Java Script (20)

20070407 Rit2007 Xmltype Samokhvalov
20070407 Rit2007 Xmltype Samokhvalov20070407 Rit2007 Xmltype Samokhvalov
20070407 Rit2007 Xmltype Samokhvalov
 
Devclub Servicemix Jevgeni Holodkov 23 04 09
Devclub Servicemix Jevgeni Holodkov 23 04 09Devclub Servicemix Jevgeni Holodkov 23 04 09
Devclub Servicemix Jevgeni Holodkov 23 04 09
 
The Real Time Web with XMPP
The Real Time Web with XMPPThe Real Time Web with XMPP
The Real Time Web with XMPP
 
Jslunch6
Jslunch6Jslunch6
Jslunch6
 
49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)
 
XML for bioinformatics
XML for bioinformaticsXML for bioinformatics
XML for bioinformatics
 
Os Pruett
Os PruettOs Pruett
Os Pruett
 
JSON Viewer XPATH Workbook
JSON Viewer XPATH WorkbookJSON Viewer XPATH Workbook
JSON Viewer XPATH Workbook
 
Speeding up Red Team engagements with carnivorall
Speeding up Red Team engagements with carnivorallSpeeding up Red Team engagements with carnivorall
Speeding up Red Team engagements with carnivorall
 
톰캣 #05-배치
톰캣 #05-배치톰캣 #05-배치
톰캣 #05-배치
 
Sphinx on Rails
Sphinx on RailsSphinx on Rails
Sphinx on Rails
 
JSARToolKit / LiveChromaKey / LivePointers - Next gen of AR
JSARToolKit / LiveChromaKey / LivePointers - Next gen of ARJSARToolKit / LiveChromaKey / LivePointers - Next gen of AR
JSARToolKit / LiveChromaKey / LivePointers - Next gen of AR
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shell
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkejElinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
Elinvoimaa hunajasta-yleist-hunajatietoa-ja-kyttvinkkej
 
Ajax
AjaxAjax
Ajax
 
yusukebe in Yokohama.pm 090909
yusukebe in Yokohama.pm 090909yusukebe in Yokohama.pm 090909
yusukebe in Yokohama.pm 090909
 
S2Flex2
S2Flex2S2Flex2
S2Flex2
 
OpenSPARC
OpenSPARCOpenSPARC
OpenSPARC
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 

Más de Constantin Kichinsky

Прототипирование приложений в Expression Blend + Sketchflow
Прототипирование приложений в Expression Blend + SketchflowПрототипирование приложений в Expression Blend + Sketchflow
Прототипирование приложений в Expression Blend + SketchflowConstantin Kichinsky
 
Пользовательский интерфейс
Пользовательский интерфейсПользовательский интерфейс
Пользовательский интерфейсConstantin Kichinsky
 
Архитектура корпоративных систем
Архитектура корпоративных системАрхитектура корпоративных систем
Архитектура корпоративных системConstantin Kichinsky
 
Шаблоны проектирования 2
Шаблоны проектирования 2Шаблоны проектирования 2
Шаблоны проектирования 2Constantin Kichinsky
 
Шаблоны проектирования 1
Шаблоны проектирования 1Шаблоны проектирования 1
Шаблоны проектирования 1Constantin Kichinsky
 
Создание новых объектов
Создание новых объектовСоздание новых объектов
Создание новых объектовConstantin Kichinsky
 
jQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptjQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptConstantin Kichinsky
 
Django – фреймворк, который работает
Django – фреймворк, который работаетDjango – фреймворк, который работает
Django – фреймворк, который работаетConstantin Kichinsky
 
Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Constantin Kichinsky
 
Управление проектами
Управление проектамиУправление проектами
Управление проектамиConstantin Kichinsky
 
Код как низкоуровневая документация
Код как низкоуровневая документацияКод как низкоуровневая документация
Код как низкоуровневая документацияConstantin Kichinsky
 

Más de Constantin Kichinsky (20)

Brain to brain communications
Brain to brain communicationsBrain to brain communications
Brain to brain communications
 
Прототипирование приложений в Expression Blend + Sketchflow
Прототипирование приложений в Expression Blend + SketchflowПрототипирование приложений в Expression Blend + Sketchflow
Прототипирование приложений в Expression Blend + Sketchflow
 
JavaScript OOP
JavaScript OOPJavaScript OOP
JavaScript OOP
 
Пользовательский интерфейс
Пользовательский интерфейсПользовательский интерфейс
Пользовательский интерфейс
 
Архитектура корпоративных систем
Архитектура корпоративных системАрхитектура корпоративных систем
Архитектура корпоративных систем
 
Шаблоны проектирования 2
Шаблоны проектирования 2Шаблоны проектирования 2
Шаблоны проектирования 2
 
Шаблоны проектирования 1
Шаблоны проектирования 1Шаблоны проектирования 1
Шаблоны проектирования 1
 
Обработка ошибок
Обработка ошибокОбработка ошибок
Обработка ошибок
 
Создание новых объектов
Создание новых объектовСоздание новых объектов
Создание новых объектов
 
Декомпозиция
ДекомпозицияДекомпозиция
Декомпозиция
 
Design Lecture
Design LectureDesign Lecture
Design Lecture
 
jQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptjQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScript
 
Оптимизация SQL
Оптимизация SQLОптимизация SQL
Оптимизация SQL
 
Django – фреймворк, который работает
Django – фреймворк, который работаетDjango – фреймворк, который работает
Django – фреймворк, который работает
 
Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!
 
Silverlight 2
Silverlight 2Silverlight 2
Silverlight 2
 
Управление проектами
Управление проектамиУправление проектами
Управление проектами
 
Silverlight 2
Silverlight 2Silverlight 2
Silverlight 2
 
Код как низкоуровневая документация
Код как низкоуровневая документацияКод как низкоуровневая документация
Код как низкоуровневая документация
 
Imagine Cup
Imagine CupImagine Cup
Imagine Cup
 

Último

(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 

Ajax и будущее Java Script

  • 1. AJAX и будущее JavaScript Константин Кичинский kichinsky@mainfo.ru http://zelo-stroi.livejournal.com
  • 3.
  • 4.
  • 5.
  • 6. AJAX | Asynchronous JavaScript and XML
  • 8. Ajax • XMLHttpRequest — API, предоставляемое браузером и доступное через JavaScript, позволяющее передавать XML и другие текстовые данные между клиентом и сервером посредством протокола HTTP путем установления независимых и асинхронных соединений между веб- страницей на клиенте и веб-сервером.
  • 9. function ajax(url, vars, callbackFunction){ var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(quot;MSXML2.XMLHTTP.3.0quot;); request.open(quot;POSTquot;, url, true); request.setRequestHeader(quot;Content-Typequot;, quot;application/x-www-form-urlencodedquot;); request.onreadystatechange = function(){ if (request.readyState == 4 && request.status == 200) { if (request.responseText){ ext); callbackFunction(request.responseT } } } request.send(vars); }
  • 10. if( !window.XMLHttpRequest ) XMLHttpRequest = function(){ try{ return new ActiveXObject(quot;MSXML3.XMLHTTPquot;) } catch(e){} try{ return new ActiveXObject(quot;MSXML2.XMLHTTP.3.0quot;) }catch(e){} try{ return new ActiveXObject(quot;Msxml2.XMLHTTPquot;) }catch(e){} try{ return new ActiveXObject(quot;Microsoft.XMLHTTPquot;) }catch(e){} throw new Error(quot;Could not find an XMLHttpRequest alternative.quot;) };
  • 11.
  • 12. • DOM — Document Object Model, способ представления html- или xml-документа в виде объектной модели, не зависящий от платформы и языка реализации. • DOM описывает способы навигации по документу и методы доступа к значениям элементов и их атрибутам.
  • 13. <?xml version=”1.0” ?> <files> <file author='Constantin'> <address>http://files.mainfo.ru/infa_labs1.zip</address> <description>Задания на лабораторную работу №1 по информатике</description> </file> … <file author='Constantin'> <address>http://files.mainfo.ru/infa_labs10.zip</address> <description>Задания на лабораторную работу №10 по информатике</description> </file> </files>
  • 14. function parseFilesXMLDocument(filesXMLDoc) { var files = filesXMLDoc.getElementsByTagName('files').item(0); for (var iFile = 0; iFile < files.childNodes.length; iFile++) { var file = files.childNodes.item(iFile); file.author = file.getAttribute('author'); file.address = file.getElementsByTagName(' address').item(0).data; file.description = file.getElementsByTagName('description').item(0).data; addFile(file); } }
  • 15. function addFile(file) { var fileHTML = ''<div class='file'>'' + ''<span class='description'>'' + file. description + ''</span'' + ''<span class='author'>'' + file.author + ''</span>'' + ''<span class='download'>'' + ''<a href=' '' + file.address + '''>скачать</a>''; … }
  • 16. • JSON — JavaScript Object Notation, простой формат обмена данными, удобный для чтения и написания как человеком, так и компьютером, основанный на подмножестве языка JavaScript. • var jsObject = eval(' (' + jsonString + ') ');
  • 17. { files: [ { author: 'Constantin', address: 'http://files.mainfo.ru/infa_labs1.zip', description: 'Задания на лабораторную работу №1 по информатике'; }, … { author: 'Constantin', address: 'http://files.mainfo.ru/infa_labs10.zip', description: 'Задания на лабораторную работу №10 по информатике'; } ] }
  • 18. function parseFilesJSONDocument(filesJSONDoc) { var files = filesJSONDoc.parseJSON().files; for (var iFile = 0; iFile < files.length; iFile++) { addFile(files[iFile]); } }
  • 19. • E4X — ECMAScript for XML, расширение языков семества ECMASCript (включая JavaScript) для нативной (встроенной) поддержки работы с XML, позволяющей работать с XML документами, учитывая их семантику.
  • 20. function parseFilesE4XDocument(filesE4XDoc) { for each (var file in filesE4XDoc.files) { addFile(file); } } function addFile(file) { var fileHTML = ''<div class='file'>'' + ''<span class='description'>'' + file.description + ''</span'' + ''<span class='author'>'' + file.@author + ''</span>'' + ''<span class='download'>'' + ''<a href=' '' + file.address + '''>скачать</a>''; … }
  • 21. • EX4 – начиная с JavaScript 1.7 • JSON – скоро непосредственно в JavaScript, сейчас – json.org
  • 23. JavaScript 2 – ECMAScript 4 ООП • ECMASript4 поддерживает объектно- ориентированное программирование введением таких структур, как классы (class) и интерфейсы (interface) — подобно языку Java.
  • 24. JavaScript 2 – ECMAScript 4 ООП • class C extends B { function C(m) { mem = m } public function getmem() { return mem } private var mem : Object } var c : C = new C(new Date)
  • 25. JavaScript 2 – ECMAScript 4 ООП • interface I { function meth(int) : int } class B implements I { public function meth(a : int) : int { return a * a } }
  • 26. JavaScript 2 -- ECMAScript 4 Пакеты • Модульность приложения поддерживается пакетами (package) и пространствами имен (namespace).
  • 27. JavaScript 2 -- ECMAScript 4 namespace improved { class C { public function frob(): int {...} public improved function frob(alpha: double): double { ... } } } c.improved::frob(1.2) use namespace improved . . . c.frob(alpha)
  • 28. JavaScript 2 -- ECMAScript 4 package org.mozilla.venkman { class Debugger { . . . } class Inspector { . . . } class StackWalker { . . . } } import org.mozilla.venkman. // use Debugger, Inspector, etc. freely
  • 29. JavaScript 2 -- ECMAScript 4 Строгие типы данных • Программирование больших проектов упрощается за счет введения строгих типов данных, определяемых классами и интерфейсами.
  • 30. JavaScript 2 -- ECMAScript 4 Оптимизация времени и пространства • Строгая типизация облегчает раннее связывание точек вызова и вызываемых из них методов, что потенциально уменьшает стоимость вызова методов по сравнению с ES3.
  • 31. JavaScript 2 -- ECMAScript 4 Данные • Параметризованные классы, Array[[T]] для Array типа T • объекты с геттер и сеттер-методами, • Типизация функций function f(a : int, b : String, c : Object) : RetType { // arguments are guaranteed to match types // return value must convert to or match RetType }
  • 32. JavaScript 2 -- ECMAScript 4 • Структурные типы type Q = {p: int, q: String} type R = {p: int, q: String, r: Boolean} type A = [int, String, Boolean, Object] • Функциональный тип данных type F = function (int, String, Boolean): Object type G = function (int, Object, Object): Number Объединения type U = (R, A, F) • function f(a : int, b : String, ...rest) { // rest is of type Array, contains actual trailing arguments }
  • 33. JavaScript 2 -- ECMAScript 4 • Групповые присваивания // swap, rotate, permute in general [a, b] = [b, a] [p, q, r] = [q, r, p] • // destructure a triple into fresh vars var [s, v, o] = db.getTriple() • let {'Title': title, 'Height': height, 'Width': width} = jsonResult • for (let [key, {'Title':title, 'FileSize':size}] in dict) print(key, title, size)
  • 34. JavaScript 2 -- ECMAScript 4 • Итераторы • let it = Iterator([quot;meowquot;, quot;oinkquot;, quot;woofquot;]) • it.next() returns [0, quot;meowquot;] • it.next() returns [1, quot;oinkquot;] • it.next() returns [2, quot;woofquot;] • for (let i in it) print(i)
  • 35. JavaScript 2 -- ECMAScript 4 • Генераторы • function count(n : int) { for (let i = 0; i < n; i++) yield i } • var gen = count(10) • gen.next() returns 0; . . .; gen.next() returns 9 gen.next() throws StopIteration
  • 36. JavaScript 2 -- ECMAScript 4 • Заполнение массивов • let squares = [i * i for (i in count(10))] print(squares) => quot;0,1,4,9,...,81« • let odd_squares = [i * i for (i in count(10)) if (i % 2)] • return [i * j for (i in it1) for (j in it2) if (i != j)]
  • 37. JavaScript 2 -- ECMAScript 4 • Операторы • class Complex { var real:Number, imag:Number; public static function +(a:Object, b:Object):Complex { if (a is Complex && b is Complex) return new Complex(a.real + b.real, a.imag + b.imag) if (b == null) return (a is Complex) ? a : new Complex(a) return intrinsic::+(a, b) } . . . }
  • 38. 0.1 + 0.2 === 0.3, а не 0.30000000000000004