SlideShare a Scribd company logo
1 of 262
Download to read offline
JavaScriptの進化	

  maruyama097

  丸山不二夫
Agenda I 進化の概観	
o  I-1 JavaScriptの適用範囲の拡大
 n    ブラウザー・サーバー内言語としての誕生
 n    jQueryの成功 -- WebのAJAX世代
 n    HTML5への期待の拡大
 n    Node.js -- クライアントからサーバーへ
 n    JavaScriptの繁栄
o  I-2 JavaScriptの言語機能の拡大
 n  Intel RiverTrail – Multi-Coreへの対応
 n  Google Dart – 新しいWeb言語の提案
 n  Microsoft TypeScript – 新しい標準?
Agenda II 言語としての進化	
o  II-1 JavaScriptの言語としての本来の特徴
  n  ホスト環境内言語
  n  オブジェクト指向:Prototype-Based Inheritance
  n  関数型言語
o  II-2 JavaScript言語の進化
  n    jQuery -- 非同期・関数型の展開
  n    Node.jsの飛躍 -- ホスト環境からの脱却
  n    RiverTrail -- ParallelArrayパターン
  n    Dartの問題提起 -- JavaScriptはScaleしない
  n    TypeScriptの目指すもの
“Initially, however, many professional
programmers denigrated the language
because its target audience was web
authors and other such "amateurs",
among other reasons.”

              --- JavaScript Wikipedia
“Java is a blue collar language. It’s not
PhD thesis material but a language for
a job. Java feels very familiar to many
different programmers because we
preferred tried-and-tested things.”

    --- “The Feel of Java” James Gosling
               IEEE Computer, June 1997
“Much of the relative simplicity of Java is
— like for most new languages—partly an
illusion and partly a function of its
incompleteness. As time passes, Java will
grow significantly in size and complexity.
It will double or triple in size and grow
implementation-dependent extensions or
libraries.”

             — Bjarne Stroustrup, ≤ 2/97
Part I   進化の概観	


   細かな技術的な議論に入る前に、大雑把に、
   JavaScriptの発展を、現象として概観しよう。
   最初に、その領域の拡大の歴史をみておこう。
   そして、最近、活発に行われている、言語機
   能の強化の動きをみることにしよう。
進化の概観
JavaScriptの適用範囲の拡大	


  p  ブラウザー・サーバー内言語としての誕生
  p  jQueryの成功 -- WebのAJAX世代
  p  HTML5への期待の拡大
  p  Node.js -- クライアントからサーバーへ
  p  JavaScriptの繁栄
Webブラウザー・
Webサーバー内言語としての誕生


 JavaScriptは、1995年、NetScapeのブラ
 ウザー内の言語として生まれた。
 indeed, there are no provisions in this
 specification for input of external data or
 output of computed results. ECMA 262 3rd
JavaScriptの誕生	
o  Author Brendan Eich
o  1994年 Mocha, LiveScript
o  1995年 12月4日 プレスリリース
o  1996年 3月 Version 1.0
              on NetScape 2.0
o  1996年 8月 Version 1.1
              on NetScape 3.0
o  1998年 10月 1.3 ECMA-262 1st + 2nd
o  2000年 11月 1.4 ECMA-262 3rd
o  2010年  7月 1.8.5 ECMA-262 5th
1995年12月4日 プレス・リリース	




http://web.archive.org/web/20070916144913
/http://wp.netscape.com/newsref/pr/newsrelease67.html
jQueryの成功
 -- WebのAJAX世代	


  JavaScriptの大きな成功は、AJAXの登場に
  よってもたらされた。それはまた、jQueryの
  成功と、ほぼ重なっていた。
  jQuery is designed to change the way that
  you write JavaScript.
jQuery	
o  Author John Resig
   now led by Dave Methvin
o  2006年1月 at BarCamp NYC
o  1.0    August 26, 2006 	
	
o  1.1    January 14, 2007
  ... ...
o  1.8.0 August 9, 2012    	
o  1.8.3 November 13, 2012 	
o  1.9.0 early 2013
o  2.0    early 2013
JavaScript Library 利用状況	
o  jQuery      91%   o  Prototype  13%
o  Modernizr 58%     o  Ext.js     11%
o  underscore.js     o  MooTools   10%
              33%     o  KnockoutJS 10%
o  backbone.js 30%   o  Sencha Touch
o  Raphael.js 19%                   10%
o  YUI         15%   o  AngularJS   8%
o  Google Closure    o  Ember       6%
                15%   o  Dojo        6%
o  Zepto       13%   o  Kendo UI     4%
HTML5への期待の拡大	


 JavaScriptへの期待は、新しいWeb標準で
 あるHTML5への期待によって、更に、拡大し
 てきた。JavaScriptは、Webの世界の標準
 言語としての地位を確立しつつある。
HTML5	
o  2008 - First Public
           Working Draft
o  2011 - Last Call
o  2012 - Working Draft
o  Plan 2014
W3C HTML5

                      Multi Media
                      HTML5 Forms
                      HTML5 Parser
                      Mouse Key ev.
                      Offline Support
                      XHTML
                      WAI ARIA
                      Semantic Element
                      	



Mozilla浅井さんの資料、”Pure Web Apps”より。
http://www.slideshare.net/dynamis
WHATWG HTML

Canvas
Web Messaging
Web Socket
Server Setn Evnt
Web Storage
Web Workers
Micro Data
CSS3

Media Queries
Layout
Flex Box
Transform
Animation
Regions
WebGL
SVG
SMIL
GeoLocation
Vibration
Orientation
SPDY
XHR2
DNT
FileAPI
CSP
ECMA Script
Indexed DB
XPath
WOFF
DOM4
MathML
RSS
OGP
Node.js 
 -- クライアントからサーバーへ



 Node.jsは、JavaScriptの適応範囲をサー
 バーへと広げた。それは、JavaScriptのブラ
 ウザー内言語からの脱却を意味している。
 Node's goal is to provide an easy way to
 build scalable network programs
Node.js	
o  Author Ryan Dahl
o  2009年5月 v0.0.1
o  2009年11月 JSConf EUで発表
o  2009.06.11, Version 0.0.3 (GitHub)
o  2010.08.20, Version 0.2.0
o  2011.02.10, Version 0.4.0
o  2011.11.04, Version 0.6.0
o  2012.06.25, Version 0.8.0
      ... ...
o  2012.10.24, Version 0.9.3 (Unstable)
CommonJS 	
o  January 2009: "ServerJS"
    Kevin Dangoor
o  March 2009:
    CommonJS API 0.1
o  April 2009:
    JSConf in Washington, DC.
o  August 2009: The group name was formally
    changed to “CommonJS”
JavaScriptの繁栄	


  JavaScriptは、現在、大きな繁栄の時期を迎
  えている。言語のスピードは、ネーティブに迫
  るほど早くなり、無数のライブラリーが生まれ
  ている。
ブラウザー内の
JavaScriptの
スピードアップ
http://v8-io12.appspot.com/#94
958種のライブラリー !!
List of languages
that compile to JS 200種類以上	
o  CoffeeScript Family (& Friends)
o  JavaScript Extensions
  n  Security enforcing JavaScript
  n  Static typing
  n  Synchronous to Asynchronous JavaScript
      Compilers (CPS)
  n  JavaScript Language Extensions
o  Ruby, Python, Perl, Java/JVM, Scala,
    C# .NET, Lisp Schema, OCaml, Haskell,
    Smalltalk, C/C++. Basic, Pascal, Go
    https://github.com/jashkenas/coffee-script/wiki/
    List-of-languages-that-compile-to-JS
進化の概観
JavaScriptの言語機能の拡大	


 p  Intel RiverTrail – Multi-Coreへの対応
 p  Google Dart – 新しいWeb言語の提案
 p  Microsoft TypeScript – 新しい標準?
Intel RiverTrail
  -- Multi-Coreへの対応


  RiverTrailは、デバイスのマルチコアのパ
  ワーをブラウザーで活用することを目的とした
  JavaScriptの拡張である。
  https://github.com/rivertrail/rivertrail/wiki
RiverTrail 	
o  Stephan Herhut
    Richard L. Hudson
    Jaswanth Sreeram
o  2011年9月 IDF 2011で発表
Presented by Justin Rattner, in IDF 2011
Google Dart
– 新しいWeb言語の提案	


 Dartは、Googleによる、JavaScriptに代わる
 新しいWeb言語の提唱である。
 Dart brings structure to web app engineering
 with a new language, libraries, and tools.
 http://www.dartlang.org
Dart	
o  Lars Bak
    Kasper Lund
    Seth Ladd
    Eli Brandt
    ...
o  2011年10月
    GOTO Conferenceで発表
http://www.dartlang.org/slides/
Microsoft TypeScript
 -- 新しい標準?	


  TypeScriptは、新しいJavaScriptの標準で
  あるECMA6を意識した、Microsoftによる、
  JavaScriptの拡張の試みである。
  Starts from JavaScript, Ends with JavaScript
TypeScript	
o  Anders Hejlsberg
    Steve Lucco
    Luke Hoban
    ...
o  2012年10月1日 発表
Part II   言語としての進化	


   ここでは、まず、JavaScriptが言語として、本
   来持っていたいくつかの特質に注目しよう。
   ついで、先に概観した言語の発展の歴史の節
   目が、こうした特質についての言語としての進
   化の節目でもあることを確認する。
JavaScriptの
言語としての本来の特徴	


 p  ホスト環境内言語
 p  オブジェクト指向:Prototype-Based
     Inheritance
 p  関数型言語
JavaScriptの
言語としての本来の特徴	


 p  ホスト環境内言語        Node.jsでの見直し
 p  オブジェクト指向:Prototype-Based
     Inheritance    TypeScriptでの発展
 p  関数型言語  jQuery,Node.jsでの展開
ECMA 262 6th?	
o  ECMAScript is a vibrant language and
    the evolution of the language is not
    complete. Significant technical
    enhancement will continue with future
    editions of this specification.
ホスト環境内言語	


 JavaScriptの最大の特徴の一つは、当初は、
 自立した言語としてではなく、特定のホスト環
 境内で働く言語として設計されたことにある。
ホスト環境内言語
ブラウザー内のWeb記述言語	
o  当初は、Webブラウザーだけではなく、Webサーバーで
    も動くことが期待されていた。
o  実際には、Webブラウザー内で動く、Web記述言語とし
    て、いわば、ブラウザーとの共生関係の下で、ブラウザー
    とともに発展してきた。Webブラウザーが、JavaScriptの
    環境を提供している。
o  Webアプリのフレームワークが想定しているように、Web
    ブラウザーが、アプリの唯一のユーザー・インターフェース
    であるならば、それは言語としては、さほど大きな制限に
    ならない。
o  同時に、Thin Server Architectureのような、Webアプ
    リのフレームワーク以外でも、ブラウザーは、クライアント
    のプレゼンテーション層の担い手として重要である。
Core JavaScript Guide
October 30, 1998 Version 1.4	

o  JavaScript is Netscape’s cross-platform,
    object-oriented scripting language.
o  JavaScript is a small, lightweight
    language; it is not useful as a
    standalone language, but is designed for
    easy embedding in other products and
    applications, such as web browsers.
    Inside a host environment, JavaScript
    can be connected to the objects of its
    environment to provide programmatic
    control over them.
ホスト環境内言語 ECMA 262 3rd	
o  ECMAScript is an object-oriented programming language
    for performing computations and manipulating
    computational objects within a host environment.
o  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.	
o  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.
Web記述言語 ECMA 262 5th	
o  前ページの一項と同じ記述
o  ECMAScript was originally designed to be a
    Web scripting language, providing a
    mechanism to enliven Web pages in browsers
    and to perform server computation as part of a
    Web-based client-server architecture.
o  前ページの二項と同じ記述
o  Further, the host environment provides a
    means to attach scripting code to events such
    as change of focus, page and image loading,
    unloading, ...
ブラウザーAPIが提供する
JavaScriptの実行環境	
o  Document Object Model (DOM)
  n  ページ内のDocumentを、nodeの木構造/親子関係
      で表現したもの
  n  nodeは、オブジェクトでpropertyを持つ
o  Browser Object Model (BOM)
  n  ブラウザーをコントロールするオブジェクト群
  n  frame, history, location, XMLHttpRequest 等
o  JavaScript objects and functions
  n  JavaScriptは、DOM, BOMへのアクセスを可能にす
      る言語。
  n  それ自身のオブジェクト、関数を持つ
ブラウザーAPIが提供する
 JavaScriptの実行環境	




document.body.style.
backgroundColor = 'red’;


                      location.replace('newpage.html');



    http://javascript.info/files/tutorial/browser/JSTop.png
ブラウザーのEvent Loopの利用	
o  JavaScriptは、ブラウザーの一つのWindowに対応した
    1スレッド上で実行される。それゆえ、JavaScriptは、ス
    レッド操作命令を持たない。
o  JavaScript上のイベントは、ブラウザーのEvent Loop /
    Event queueでハンドルされる。
o  基本的には、イベントのCallback関数を、ブラウザーの
    Event queueに積み込んでいく。ブラウザーのEvent
    Loopが、定期的にEvent queueをチェックする。
o  ブラウザー内言語としての、この特別な特徴は、jQuery
    で全面的に利用され、ブラウザー内言語からの脱却であ
    るnode.jsのアーキテクチャに、直接的な影響を与えた。
オブジェクト指向:
Prototype-Based Inheritance	


  JavaScriptのオブジェクト指向の特徴である、
  prototypeの利用は、ごく早い時期から、
  NetScape Navigator 3.0上の、JavaScript
  1.1から、実装されている。
JavaScript 1.1 HandBook 	




http://web.archive.org/web/20020611210350/
http://wp.netscape.com/eng/mozilla/3.0/handbook/
javascript/index.html
オブジェクト指向:
Prototype-Based Inheritance	
o  Each constructor has a Prototype
    property that is used to implement
    prototype-based inheritance and shared
    properties.           ECMAScript 3rd



o  Each constructor is a function that has
    a property named ―”prototype” that is
    used to implement prototype-based
    inheritance and shared properties.
                          ECMAScript 5th
Prototype	
o  Every object created by a constructor
    has an implicit reference (called the
    object‘s prototype) to the value of its
    constructor‘s ―”prototype” property.
o  Furthermore, a prototype may have a
    non-null implicit reference to its
    prototype, and so on; this is called the
    prototype chain
Object/Prototype Relationships
Example	
var today = new Date()
var birthday = new Date(95,12,17)
Date.prototype.description=null
today.description="Oh what a beautiful
mornin'"
birthday.description="The day you were
born”
startDate=new Date()
startDate.description=“Started the daily
grind”
Example 1: Add a property to a
  user-defined object. 	
function Car(make, model, year) {
  this.make = make
  this.model = model
  this.year = year
}

var myCar = new Car("Acura", "Integra", 1987)
Car.prototype.wheels = 4      // no 3-wheelers please!

if (myCar.wheels == 4)
   document.write("The car myCar has ",
                   myCar.wheels, " wheels.”)
Example 2: Add a method to
 String objects.	
var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")

// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
  var s = "", t = this.toString()
  while (--n >= 0) s += t
  return s
}
String.prototype.rep = str_rep

// Display the results
document.write("<P>s1.rep(3) is " + s1.rep(3))  // "aaa"
document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb"
document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”
Prototype.js
Class.create() -- Obsolete	
var Person = Class.create();
Person.prototype = {
 initialize: function(name) {
   this.name = name;
 },
 say: function(message) {
   return this.name + ': ' + message;
 }
};

var guy = new Person('Miro');
guy.say('hi');
// -> "Miro: hi”
Prototype.js
 Object.extend() -- Obsolete	
var Pirate = Class.create();
// inherit from Person class:
Pirate.prototype = Object.extend(new Person(), {
  // redefine the speak method
  say: function(message) {
    return this.name + ': ' + message + ', yarr!';
  }
});

var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"
Prototype.js
Class.create() – New!	
// properties are directly passed to `create` method
var Person = Class.create({
 initialize: function(name) {
   this.name = name;
 },
 say: function(message) {
   return this.name + ': ' + message;
 }
});

// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
 // redefine the speak method
 say: function($super, message) {
   return $super(message) + ', yarr!';
 }
});
Prototype.js
    Class.create() Mixin – New!	
var Vulnerable = {
 wound: function(hp) {
   this.health -= hp;
   if (this.health < 0) this.kill();
 },
 kill: function() {
   this.dead = true;
 }
};

// the first argument isn't a class object, so there is no inheritance ...
// simply mix in all the arguments as methods:
var Person = Class.create(Vulnerable, {
 initialize: function() {
   this.health = 100;
   this.dead = false;
 }
});
TypeScript Class
   ==> JavaScript 	
class BankAccount {
  balance = 0;
  deposit(credit: number) {
     this.balance += credit;
     return this.balance;
  }                        var BankAccount = (function () {
} 	
                         function BankAccount() {
                               this.balance = 0;
                             }
                             BankAccount.prototype.deposit =
                             function(credit) {
                               this.balance += credit;
                               return this.balance;
                             };
                             return BankAccount;
                           })();
Dart Class
  ==> JavaScript 	
class Point {
  var x, y;
  Point(this.x, this.y);
  toString() => "($x,$y)”;
}	
               Dartは、prototypeを使っていない	
Isolate.$defineClass("Point", "Object", ["x", "y"], {
  toString$0: function() {
    return '(' + $.toString(this.x) + ',' +
              $.toString(this.y) + ')’;
  }
});
オブジェクト指向言語としての
JavaScript	
o  現時点で、JavaScriptの言語としての進化の、
    一つの焦点になっているのが、大規模開発を意
    識した、JavaScriptのオブジェクト指向言語とし
    ての機能強化である。
o  JavaScriptの発展を目指すTypeScriptも、
    JavaScriptの対抗言語となることも辞さない
    Dartも、このことを強く意識している。
o  ただ、確認しておきたいことは、JavaScriptが本
    来持っていた、prototypeベースのオブジェクト
    指向が、極めて柔軟で強力なオブジェクト指向の
    枠組みを提供しているということである。
関数型言語としてのJavaScript	


  prototypeと同様に、functionは、言語のご
  く初期から、JavaScript 1.1から導入された。
オブジェクト指向
Class型とPrototype型	
o  Class型のJavaでは、クラスは、フィールドとメ
    ソッドによって定義され、クラスのインスタンスとし
    てのオブジェクトは、基本的にフィールドの値で特
    徴付けられる。
o  Prototype型のJavaScriptのオブジェクトは、そ
    れが持つプロパティのオブジェクトによって定義さ
    れる。JavaScriptでは、フィールドとメソッドの区
    別は、相対的なものである。
o  重要なのは、JavaScriptでは、functionもオブ
    ジェクトであり、プロパティの値になること。
JavaScript 1.1 HandBook 	




http://web.archive.org/web/20020611210350/
http://wp.netscape.com/eng/mozilla/3.0/handbook/
javascript/index.html
Operator, Function	
o  ECMAScript also defines a set of built-in
    operators that may not be, strictly
    speaking, functions or methods.  
                      ECMAScript 3rd



o  a function is a callable object.
    A function that is associated with an
    object via a property is a method.
                      ECMAScript 5th
JavaScriptで、functionは、
第一級の市民	
o  JavaScript 1.0では、functionは、operatorと
    呼ばれていたようだ。
o  JavaScriptの特徴として、functionが第一級の
    市民であることの認識は、当初からあったもので
    はなく、歴史的に形成されてきたように見える。
o  おそらく、jQueryの非同期のCallbackの実装ス
    タイルが広く知られたことが、大きな転機になった
    ように思える。
o  もちろん、Prototype型のオブジェクト指向が、も
    ともと、それを可能にしていたのではあるが。
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError
    ajaxSuccess ajaxSend".split( " " ), function( i, o ){
    jQuery.fn[ o ] = function( f ){
        return this.on( o, f );
    };
});
jQuery.each( [ "get", "post" ], function( i, method ) {
    jQuery[ method ] = function( url, data, callback, type ) {
        // shift arguments if data argument was omitted
        if ( jQuery.isFunction( data ) ) {
             type = type || callback;
             callback = data;
             data = undefined;
        }
        return jQuery.ajax({
             type: method,
             url: url,
             data: data,
             success: callback,
             dataType: type
        }); }; });
関数型言語としてのJavaScript	
o  jQuery, node.jsという発展を通じて、関数型言
    語としてのJavaScriptの特質は、その進化を牽
    引してきた。今日でも、それは、JavaScriptの
    もっとも魅力的で強力な特徴の一つになっている。
o  オブジェクト指向言語であると同時に、関数型言
    語でもあるという、JavaScriptの二つの側面が、
    今後、どのように発展していくかは、興味深いもの
    がある。
o  次回のセミナーでは、関数型言語としての
    JavaScriptに、あらためて焦点を合わせたいと
    考えている。
JavaScript言語の進化	


  p  jQuery -- 非同期・関数型の展開
  p  Node.jsの飛躍 -- ホスト環境からの脱却
  p  RiverTrail -- ParallelArrayパターン
  p  Dartの問題提起 -- JavaScriptはScale
      しない
  p  TypeScriptの目指すもの
jQuery -- 非同期・関数型の展開


  jQueryは、Structured Web世代の
  AJAX(Asynchronous JavaScript +
  XML)技術を支える代表的なJavaScriptラ
  イブラリーである。そこではDOMは、HTTPの
  Request/Responseを待たずに、非同期に
  書き換えられる。
jQueryとは何か?	
o  jQuery is a fast and concise JavaScript
    Library that simplifies HTML document
    traversing, event handling, animating,
    and Ajax interactions for rapid web
    development.
o  jQuery is designed to change the way
    that you write JavaScript.
DOM Tree
Parent/Children
CSS Selector
AJAX用のメソッド	
o  jQuery.get()
   n  Load data from the server using a HTTP GET request.
o  jQuery.getJSON()
   n  Load JSON-encoded data from the server using a GET
       HTTP request.
o  jQuery.getScript()
   n  Load a JavaScript file from the server using a GET
       HTTP request, then execute it.
o  .load()
   n  Load data from the server and place the returned
       HTML into the matched element.
o  jQuery.post()
   n  Load data from the server using a HTTP POST
       request.
AJAX Event	
o  ajaxStart (Global Event)
   n    beforeSend (Local Event)
   n    ajaxSend (Global Event)
   n    success (Local Event)
   n    ajaxSuccess (Global Event)
   n    error (Local Event)
   n    ajaxError (Global Event)
   n    complete (Local Event)
   n    ajaxComplete (Global Event)
o  ajaxStop (Global Event)
jQuery.ajax( url [, settings] )	
o  Ajax関連の関数の実装には、関数ajax()が使
    われている。
o  この関数は、引数一つだけをとるのだが、次のよ
    うに、Hashを渡すことで、多数のオプションを指
    定出来る。	
$.ajax( {
         url: "script.php",
        type: "post",
     success: function(result) { alert(result); }

     });
ajax()のオプションの例	
o  async : boolean   o  dataType : string
o  cache : boolean   o  error : function
o  complete :        o  jsonp : string
    function          o  scriptCharset :
o  contentType :         string
    string            o  success : function
o  data : object,    o  timeout : number
    string            o  type : string
o  dataFilter :
                      o  url : string
    function
                      o  xhr : function
Ajaxの呼び出し例	

<div id = "form">
  <input type = "text" id = "name">
  <input type = "text" id = "email_address">
  <input type = "text" id = "number">
  <input type = "submit" onclick =
       "$.ajax({url:'submit.php' +
         getform('input', '#form'),
         type:'post'})">
</div>
function getform(input, form)
{
   /* Copyright Greg Sidelnikov - www.learnjquery.org -
     greg.sidelnikov@gmail.com. You can use it in your own
     projects, retain this line, if you wish to give me credit.
   */

    var ret = "?";
    var Length = $(element, parent).length;
    var idnamelist = new Array();
    var idvaluelist = new Array();
    for (var i = 0; i < Length; i++)
    {
       idnamelist[i] = $(element, parent)[i].id;
       idvaluelist[i] = $(element, parent)[i].value;
       ret = idnamelist[i] + '=' + idvaluelist[i];
       if (i < Length - 1)
           ret += "&";
    }
}
EventHandlerのbind/unbind	
p  要素に、特定のイベントのEventHandlerを設定
    しておくことが出来る。
p  要素上で、そのイベントが発生した特、
    EventHandlerが呼び出される。

  var handler = function() {
   alert(‘ Hello World!');
  };
  $(’#greet').bind('click', handler);
  $(’#greet').unbind('click', handler);
eventの「名前」と、同名の関数	
o  次の二つは、同じ働きをする。
 $(window).bind( “load”, function()  
   { alert('Window finished loading.'); } );
 $(window).load( function()   
  { alert('Window finished loading.'); } );
jQueryの特徴	
o  jQueryの大きな特徴は、AJAXを、イベント・ドリ
    ブンで非同期な関数呼び出しのスタイルで実装し
    たことにある。そこでは、JavaScriptの関数型言
    語としての特質が、全面的に利用されている。
o  JavaScriptは、もともと、Single-Threadで走っ
    ているので、それは、Multi-threadではない、
    Single-Thread上の、「並列」処理という、一見
    奇妙な形を取る。
o  ただ、こうした、アプローチは、孤立したものでは
    ない。ErlangやScalaのAkkaも、原理的には同
    じアプローチだと言っていい。
jQueryの特徴	
o  もともと、一つのCPUを取ってみれば、同時には
    一つの処理しか行えない。Multi-Process /
    Multi-Thredといった「並行」処理は、OSのタイ
    ム・スライスが生み出す、擬似的なものである。
o  その点は、多数のCPUが協調動作する、「分散」
    処理の「並列性」とは、別のものである。
o  ブラウザー内言語という性格もあって、jQueryの
    疑似並列性は、OSによってではなく、ホスト環境
    としてのブラウザーのEvent Loop / Event
    Queueによって担保されている。
Node.jsの飛躍
-- ホスト環境からの脱却	


 JavaScriptの、この間の言語としての進化で、
 最大のものは、Node.jsの登場である。
 ブラウザーというホスト環境に依存していた言
 語は、そこからの脱却を始める。EventLoop
 を自分自身で持つことによって。
クライアントからサーバーへ?	
o  今回の講演の前半では、node.jsの登場を、「ク
    ライアントからサーバーへ」と、JavaScriptの適
    応範囲の拡大として、特徴付けた。
o  ただ、node.jsをよく見ていくと、node.jsの登場
    を、JavaScriptの側からだけみる、こうした見方
    は、いささか狭いものであることに気付く。
o  基本的には、JavaScriptの内部の問題ではなく、
    より一般的な、イベント・ドリブンで非同期な入出
    力に対する関心の高まりが背景にあることがわ
    かる。
2009年11月 JSConf
 Ryan Dahlの登場	
o  ここでは、node.jsの爆発的な拡大の起点となった、
    2009年ベルリンで行われた、JSConfでのnode.js
    の創始者Ryan Dahlの講演の一部を見てみよう。
          “Node.js,
Evented I/O for V8 Javascript”
                  by Ryan Dahl
 n  http://jsconf.eu/2009/speaker/
     speakers_selected.html#entry-3356
 n  http://s3.amazonaws.com/four.livejournal/
     20091117/jsconf.pdf
I/O は、違ったやり方で
行われる必要がある。	
o  多くのWebアプリは、次のようなコードを使う。
    var result =
      db.query("select * from T");
    // use result
o  データベースを検索している間、ソフトウェアは何
    をしているのだろう? たいていの場合、ただレス
    ポンスを待っているだけである。
o  それに加えて、IOによる遅延は、コンピュータの
    能力と比較すると、次のように、巨大なものである。

http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf
I/O による遅延	
l    L1: 3 cycles
l    L2: 14 cycles
l    RAM: 250 cycles
l    DISK: 41,000,000 cycles
l    NETWORK: 240,000,000 cycles

o  別の例を挙げよう。サーバーのパフォーマンスも
    実装によって大きな違いが生まれている。次のズ
    は、AppacheとNGINXを比較したものである。
Apache vs NGINX
違いはどこにあるのか?	




o  Apache はコネクションあたり一つのスレッドを使っている
    が、NGINXは、スレッドを使っていない。それは、event
    loopを使っている。
o  コンテキストの切り替えは、ただで出来る訳では
    ないし、スレッドの実行用のスタックは、メモリーを
    食う。大規模な並列処理では、それぞれのコネク
    ション毎にOSのスレッドを使うことは出来ない。グ
    リーン・スレッドやコルーティンは、こうした状況を
    劇的に改善出来る。
o  しかし、I/Oの実行を維持しているという幻想を生
    み出す、入り組んだメカニズムが、依然として存
    在している。スレッドによる並列性は、漏れの多い
    抽象である。
var result = db.query("select..");	
o  このようなコードは、全体のプロセスをブロックす
    るか、複数のプロセスの実行をスタックさせること
    になるかのいずれかである。
o  しかし、次のようなコードでは、プログラムは、すぐ
    にevent loopに戻ることが可能である。どのよう
    なメカニズムも必要としない。
  db.query("select..", function (result) {
     // use result
  });	

o  これが、I/Oが行われるべき方法である。
o  では、何故、誰もがevent loopやCallbackや
    Non-BlokingI/Oを使わないのだろうか?
文化的偏見	
o  我々は、I/Oを次のように行うと教えられてきた
 1.  puts("Enter your name: ");
 2.  var name = gets();
 3.  puts("Name: " + name);
o  我々は、入力を要求されたら、それが終わるまで
    何もしないと教えられてきた。次のようなコードは、
    複雑すぎるとして、退けられてきた。
 1.  puts("Enter your name: ");
 2.  gets(function (name) {
 3.      puts("Name: " + name); });
インフラの不在	
o  それでは、何故、誰もが event loopを使わない
    のだろう?
o  シングル・スレッドのevent loopは、I/Oが non-
    blockingであることを要求するのだが、ほとんど
    のライブラリーはそうなっていない。
  n  POSIX async file I/O は使えない.
  n  Man pagesは、関数がディスクにアクセスすることが
      あることを触れていない。 (e.g getpwuid())
  n  Cに、クロージャーや無名関数がないことが、コール
      バックを難しくしている。
  n  データベースのライブラリーは(e.g. libmysql)、非同
      期のサポートをしていない。
JavaScript	
o  Javascriptは、event loopと一緒に使われるよ
    うに、特別にデザインされた言語である。
  n  無名関数、クロージャー
  n  同時には、一つだけのコールバック
  n  DOMのイベントコールバックを通じたI/O
o  JavaScriptのカルチャーは、既に、イベント中心
    のプログラミングの準備ができている。
node.js project:	

高度な並列プログラムを記述する、純粋
にイベント中心で、non-blockingなイン
フラを提供すること。
Design Goals	
o  No function should direct perform I/O.
  n  To receive info from disk, network, or
      another process there must be a callback.
o  Low-level.
  n  Stream everything; never force the
      buffering of data.
  n  Do not remove functionality present at the
      POSIX layer. For example, support half-
      closed TCP connections.
  n  Have built-in support for the most important
      protocols: TCP, DNS, HTTP
Design Goals	
o  Support many HTTP features.
  n  Chunked requests and responses.
  n  Keep-alive.
  n  Hang requests for comet applications.
o  The API should be both familiar to
    client-side JS programmers and old
    school UNIX hackers.
o  Be platform independent.
An Introduction to libuv
 http://nikhilm.github.com/uvbook/An
	
 %20Introduction%20to%20libuv.pdf
	




       http://vimeo.com/51637038
Libuv	
o  libuv enforces an asynchronous, event-
    driven style of programming.
o  Its core job is to provide an event loop
    and callback based notifications of I/O
    and other activities.
o  libuv offers core utilities like timers,
    non-blocking networking support,
    asynchronous file system access, child
    processes and more.
Event loops	
o  In event-driven programming, an
    application expresses interest in certain
    events and respond to them when they
    occur.
o  The responsibility of gathering events
    from the operating system or monitoring
    other sources of events is handled by 
    libuv, and the user can register callbacks
    to be invoked when an event occurs.
o  The event-loop usually keeps running 
    forever.
#include   <stdio.h>
#include
#include
           <fcntl.h>
           <unistd.h>
                                  libuvスタイルでの
#include   <uv.h>                     catの実装	
void on_read(uv_fs_t *req);
                                   open, red, writeの
uv_fs_t open_req;
uv_fs_t read_req;
                        イベントの      libuv版は、第一引数に
                        ようなもの	
uv_fs_t write_req;                 loopを取る。最終引数は
                                   callback	
char buffer[1024];

void on_write(uv_fs_t *req) { // callbackのsigniture
   uv_fs_req_cleanup(req);
   if (req->result < 0) {
       fprintf(stderr, "Write error: %sn",
        uv_strerror(uv_last_error(uv_default_loop())));
   }
   else {
       uv_fs_read(uv_default_loop(), &read_req, open_req.result,
      buffer, sizeof(buffer), -1, on_read); // callback
   }
} // on_write callbackの中で、on_read callbackが呼ばれる
void on_read(uv_fs_t *req) { // callbackのsigniture
   uv_fs_req_cleanup(req);
   if (req->result < 0) {
       fprintf(stderr, "Read error: %sn",
       uv_strerror(uv_last_error(uv_default_loop())));
   }
   else if (req->result == 0) {
       uv_fs_t close_req;
       // synchronous
       uv_fs_close(uv_default_loop(),
           &close_req, open_req.result, NULL);
   }                                  // callbackがNULL、同期型
   else {
       uv_fs_write(uv_default_loop(),
           &write_req, 1, buffer, req->result, -1, on_write);
   }                                                  // callback
}  // on_read callbackの中で、on_write callbackが呼ばれる
void on_open(uv_fs_t *req) { // callbackのsigniture
   if (req->result != -1) {
       uv_fs_read(uv_default_loop(), &read_req, req->result,
                buffer, sizeof(buffer), -1, on_read); // callback
   }
   else {
       fprintf(stderr, "error opening file: %dn", req->errorno);
   }
   uv_fs_req_cleanup(req);
} // on_open callbackの中で、on_read callbackが呼ばれる

int main(int argc, char **argv) {
   uv_fs_open(uv_default_loop(),
      &open_req, argv[1], O_RDONLY, 0, on_open); // callback
   return 0;
} // openは、on_open callbackを呼んで、すぐループに入る。
RiverTrail
 -- ParallelArray パターン	


  River Trail gently extends JavaScript
  with simple deterministic data-
  parallel constructs
RiverTailの背景	
o  Intel LabのRiverTrailプロジェクトは、Webア
    プリにおいて、データの並列計算を可能にするも
    のである。
o  Webブラウザーが、ユーザーのコンピューティン
    グの窓口になっている世界では、最良のユー
    ザー・エクスペリエンスを提供するために、ブラウ
    ザーのアプリケーションは、利用可能な全ての計
    算資源の力にてこ入れをしなければならない。
API デザイン
三つの柱のアプローチ	
o  ParallelArray と呼ばれるデータの値を保持
    する型
o  mapのような、並列計算を実装した、いくつかの
    prototypical methodsと呼ばれる
    ParallelArrayのメソッド
o  典型的には、一つのデータ要素を返し、
    ParallelArrayのような構成物に渡される
    elemental function のコンセプト
ParallelArray Constructor	
pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]);
  // <<0,1>, <2,3>, <4.5>>
pa2 = new ParallelArray(pa1);
new ParallelArray(<0,1>, <2,3>);
  // <<0,1>,<2,3>>
new ParallelArray(3,
      function(i){return [i, i+1];});
  // <<0,1><1,2><2,3>>
new ParallelArray([3,2],
      function(iv){return iv[0]*iv[1];});
  // <<0,0><0,1><0,4>>
new ParallelArray(canvas);
Prototype Methods	
var source = new ParallelArray([1,2,3,4,5]);
var plusOne = source.map(
          function inc(v) { return v+1; });
   // <2,3,4,5,6>

var source = new ParallelArray([1,2,3,4,5]);
var plusOne = source.combine(
           function inc(i) { return this.get(i)+1; });
   // <2,3,4,5,6>
var source = new ParallelArray([1,2,3,4,5]);
var reverse = source.combine(function rev(i) {
return this.get(this.length-i[0]-1); });
   // <5,4,3,2,1>
Prototype Methods	
var source = new ParallelArray([1,2,3,4,5]);
var sum = source.reduce(
         function plus(a,b) { return a+b; });
   // 15

var source = new ParallelArray([1,2,3,4,5]);
var psum = source.scan(
           function plus(a,b) { return a+b; });
   // <1, 3, 6, 10, 15>
Prototype Methods	
var source = new ParallelArray([1,2,3,4,5]);
var even = source.filter(
     function even(iv) {
        return (this.get(iv) % 2) == 0; });
   // <2,4>

pa = new ParallelArray([ [1,2], [3,4] ])
   // <<1,2>,<3,4>>
pa.flatten()
   // <1,2,3,4>
Prototype Methods	
var source = new ParallelArray([1,2,3,4,5]);
var indices = [0, 1, 2, 3, 4];
var identity = source.scatter(indices);
  // <1, 2, 3, 4, 5>
var reorder = source.scatter([4,0,3,1,2]);
  // <2, 4, 5, 3, 1>

  // if there is a conflict use the max.
  // use 33 as a default value.
var reorder = source.scatter([4,0,3,4,2], 33,
          function max(a, b) {return a>b?a:b; });
  // <2, 33, 5, 3, 4>
プログラマは、どのように
並列アルゴリズムを記述しうるか?	
o  Multi-core化の進展は、特に、身近なデバイス
    上でのその進展は、普通のプログラマにとっても、
    並列アルゴリズムの必要性を意識させるきっかけ
    になるかもしれない。
o  ただ、並列アルゴリズムの実装は、難しい。
    ParallelArrayは、プログラマが、容易に並列ア
    ルゴリズムにアクセス出来るように設計された、
    パターンである。
o  Javaの新しいバージョンも、基本的には、同じ
    ParallelArrayのアプローチを採用している。
DartとTypeScript	

  これ以降の節で取り上げる、GoogleのDartと
  MicrosoftのTypeScriptは、いずれも、JavaScript
  の開発の大規模化が抱える問題の認識から出発して
  いる。それはまた、前回のセミナーで取り上げた、
  Facebookも共有しているであろう問題意識である。
  ただ、JavaScriptに対する両者のスタンスは、異なっ
  ている。JavaScriptの枠の中での発展を目指す
  TypeScriptと、JavaScriptの置き換えを目指す
  Dartという構造になる。
Dartの問題提起
-- JavaScriptはScaleしない	

  Dartは、Googleの提案する、新しいWeb言語である。
  ブラウザーを中心として対象とする領域は、
  JavaScriptと重なっている。基本的には独自のVM上
  で動くのだが、JavaScriptに変換するコンパイラーを持
  ち、JavaScriptを強く意識している。
  なぜ、GoogleはJavaScriptに代わるWeb言語を提案
  しているのだろう?
何故、Webはプログラムが難しいのか	
o    大規模の、きちんと動くアプリを書くのは、大変難しい。
o    プログラムの構造を推察するのが難しい
o    立ち上がりのパフォーマンスが、しばしば、非常に悪い。
o    (型がないことによる)意図を文書化することの困難
o    modules, packages, librariesがサポートされていな
      い。	



 Dart: Modern Web Language
 Kasper Lund
 http://www.infoq.com/presentations/Dart-A-Modern-Web-Language
それでは、何故、
我々は、Dartを作ったのか?	
o  我々は、Webプラットフォームを改善したい
 n    大規模なプログラミングの、より良いサポート
 n    とりわけ、モバイルでの迅速なアプリの立ち上げ
 n    より予測可能で、より良い実行時のパフォーマンス
 n    JavaScriptは強力なツールではあるが、危険なところ
       も持っている
o  イノベーションの勢いを維持する
 n  Webは、ファンタスティクなペースで進化し続けている
 n  開発者のツールは、水準を上げなければならない
JavaScriptは、「驚き」に満ちている	
o  沢山の沢山の、暗黙の型変換
o  間違った、あるいは、初期化しないままで値を渡
    したとき、ほとんどの関数は、理解可能な仕方で
    失敗するのではなく、とんでもない結果を返してく
    る。	




       Keep on truckin’
Dart Technical Overview
Design Goalから	
o  小さなスクリプトが、明確な構造を持たないまま、
    大規模なWebアプリに発展することがよくあるが、
    こうしたアプリは、デバッグも難しいし、メンテする
    のも難しい。
o  それに加えて、こうしたモノリシックなアプリは、
    別々のチームが独立にそのアプリについて仕事
    をしようとしても、分割が出来ない。Webアプリが
    大きくなるにつれて、生産的であることは難しくな
    る。
o  スクリプト言語が人気があるのは、その軽量な性
    格がコードを早く書くことを容易にしているからで
    ある。一般的に言って、アプリのその他の部分と
    の契約関係は、言語の構造自身というよりも、コメ
    ントによってになわれることになる。その結果、あ
    る特定のコードの一部は、そのコードを書いた本
    人以外にとっては、読むこともメンテすることも難
    しくなる。
o  既存の言語では、開発者は、静的な言語と動的
    な言語の間で選択を迫られる。伝統的な静的言
    語では、重たい沢山のツール群と柔軟ではなく束
    縛し過ぎと感じられるコーディング・スタイルが要
    求されることになる。
o  開発者は、これまで、クライアントとサーバーの両
    方をまたいだ、均質なシステムを作り出すことが
    出来なかった。Node.jsやGoogle Web
    Toolkit (GWT)といった少数の例外を除いては。
o  異なる言語とフォーマットは、退屈なコンテキスト
    の切り替えを必然的に伴い、コーディングのプロ
    セスに複雑さを付け加えている。
Technical Overview	

  Key features
  p  Classes
  p  Optional types
  p  Libraries
  p  Tooling
  http://www.dartlang.org/docs/
  technical-overview/
Design goals	
o  Create a structured yet flexible
    programming language for the web.
o  Make Dart feel familiar and natural to
    programmers and thus easy to learn.
o  Ensure that all Dart language constructs allow
    high performance and fast application
    startup.
o  Make Dart appropriate for the full range of
    devices on the web—including phones,
    tablets, laptops, and servers.
o  Provide tools that make Dart run fast across
    all major modern browsers.
interface Shape {
  num perimeter();
}

class Rectangle implements Shape {
  final num height, width;
  Rectangle(num this.height, num this.width);
 // Compact constructor syntax.
  num perimeter() => 2*height + 2*width;
// Short function syntax.
}

class Square extends Rectangle {
  Square(num size) : super(size, size);
}
import 'dart:math';

class Point {
  var x, y;
  Point(this.x, this.y);
  scale(factor) => new Point(x*factor, y*factor);
  distance() => sqrt(x*x + y*y);
}

main() {
   var a = new Point(2,3).scale(10);
   print(a.distance());
}
import 'dart:math';

class Point {
  num x, y;
  Point(num this.x, num this.y);
  Point scale(num factor)
          => new Point(x*factor, y*factor);
  num distance() => sqrt(x*x + y*y);
}

void main() {
  Point a = new Point(2,3).scale(10);
  print(a.distance());
}
Improving the DOM	


  http://www.dartlang.org/articles/
  improving-the-dom/
Use real collections	
Old	
                       New	
o  elem.hasAttribute('na   o  elem.attributes.contai
    me');                       nsKey('name');
o  elem.getAttribute('na   o  elem.attributes['nam
    me')                        e'];
o  elem.setAttribute('na   o  elem.attributes['nam
    me', 'value');              e'] = 'value';
o  elem.removeAttribute    o  elem.attributes.remo
    ('name');                   ve('name');
Use real collections /
Use Constructor	
Old	
                      New	
o  elem.hasChildNodes()   o  elem.nodes.isEmpty()
    ;                          ;
o  elem.firstChild();     o  elem.nodes[0];
o  elem.appendChild(chi   o  elem.nodes.add(child
    ld);                       );

o  document.createElem    o  new DivElement();
    ent('div');
Events	
Old	
                           New	
o  elem.addEventListene        o  elem.on.click.add(
    r('click',                      (event) =>
      (event) =>                       print('click!'));
     print('click!'), false);

o  elem.removeEventLis         o  elem.on.click.remove
    tener(                          (listener);
     'click', listener);
Events	
Old	
                       New	
o  elem.addEventListene    o  elem.on['some' +
    r(                          'name'].add(
     'some' + 'name',            (event) =>
     (event) =>                   print('dynamic!'));
       print('dynamic!'),
    false);
TypeScriptの目指すもの	


  p  Scalable
  p  Starts from JavaScript, Ends with
      JavaScript
  p  Strong Tools for Large Applications
Scalable	
o  TypeScriptは、頑健なコンポーネント作成を助
    ける為に、class, module, interfaceを提供す
    る。
o  これらの特徴を、高信頼なアプリ開発において、
    開発時に利用出来る。ただし、それらは、シンプ
    ルなJavaScriptにコンパイルされる。
o  TypeScriptの型は、ソフトウェア・コンポーネント
    間のインターフェース定義を可能とし、また、既存
    のJavaScriptライブラリーの振る舞いの洞察も
    得ることが出来る。
Starts from JavaScript, Ends
with JavaScript	
o  TypeScriptは、数百万のJavaScript開発者が今日知っ
    ている、シンタックスとセマンティックスから始まる。
o  TypeScriptでは、 既存のJavaScriptコードを利用する
    ことが出来るし、よく使われているJavaScriptライブラリと
    合体することも出来る。また、他のJavaScriptコードから
    呼び出されることも出来る。
o  TypeScriptは、どんなブラウザー上でも、node.jsでも、
    どんなES3互換の環境でも動く、クリーンでシンプルな
    JavaScriptコードにコンパイルされる。
Strong Tools for Large
Applications	
o  型は、静的チェック、シンボルベースのナビゲー
    ション、文の補完、コードのリファクタリングといっ
    た、高い生産性を持つ開発ツールと実践を、
    TypeScript開発者が行うことを可能とする。
o  これらの型は、オプショナルなものである。型推論
    は、少数の型のアノテーションでも、コードの静的
    な検証に、大きな違いをもたらすことが出来る。


TypeScript
Language Specification 	


   http://www.typescriptlang.org/
   Content/TypeScript%20Language
   %20Specification.pdf
Introduction 	
o  TypeScript is a syntactic sugar for
    JavaScript. TypeScript syntax is a
    superset of Ecmascript 5 (ES5) syntax.
    Every JavaScript program is also a
    TypeScript program.
o  TypeScript syntax includes several
    proposed features of Ecmascript 6 (ES6),
    including classes and modules.
o  TypeScript also provides to JavaScript
    programmers a system of optional type
    annotations. These type
Introduction	
o  1.1   Ambient Declarations
o  1.2   Function Types
o  1.3   Object Types
o  1.4   Structural Subtyping
o  1.5   Contextual Typing
o  1.6   Classes
o  1.7   Modules .
Ambient Declarations 	
o  An ambient declaration introduces a
    variable into a TypeScript scope, but has
    zero impact on the emitted JavaScript
    program.
o  Programmers can use ambient
    declarations to tell the TypeScript
    compiler that some other component will
    supply a variable 	
  declare var document;
  document.title = "Hello";
  // Ok because document has been declared
Function Types 	
o  TypeScript function types make it
    possible for programmers to express the
    expected signature of a function. 	
  function vote(candidate: string,
             callback: (result: string) => any)
    { // ... } 	


  A function type literal of the form
     ( ParamList ) => ReturnType
  is exactly equivalent to the object type literal
     { ( ParamList ) : ReturnType }
Object Types 	
o  TypeScript programmers use object
    types to declare their expectations of
    object behavior.
o  The following code uses an object type
    literal to specify the return type of the
    ‘MakePoint’ function 	


 var MakePoint: () => { x: number; y: number; };
Object Types : Interfaces	
o  Programmers can give names to object
    types; we call named object types
    interfaces.
o  For example, in the following code, an
    interface declares one required field
    (name) and one optional field
    (favoriteColor). 	
   interface Friend {
       name: string;
       favoriteColor?: string;
   }
interface  Friend {
    name: string;
    favoriteColor?: string;
}

function add(friend: Friend) {
   var name = friend.name;
}

add({ name: "Fred" }); // Ok
add({ favoriteColor: "blue" }); // Error, name required
add({ name: "Jill", favoriteColor: "green" }); // Ok
Structural Subtyping 	
o  Object types are compared structurally.
o  A class may optionally declare that it
    implements an interface, so that the
    compiler will check the declaration for
    structural compatibility.
interface Point {
   x: number;
   y: number;
}

function getX(p: Point) {
  return p.x;
}
class CPoint {
   constructor (
      public x: number,
      public y: number) {}
}
getX(new CPoint(0, 0)); // Ok, fields match
getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok
getX({ x: 0 }); // Error: supplied parameter does not
                   match
Contextual Typing 	
interface EventObject {
   x: number;
   y: number;
}

interface EventHandlers {
   mousedown?: (event: EventObject) => void;
   mouseup?: (event: EventObject) => void;
   mousemove?: (event: EventObject) => void;
}

function setEventHandlers(handlers: EventHandlers) { ... }
setEventHandlers({
   mousedown: e => { startTracking(e.x, e.y); },
   mouseup: e => { endTracking(); }
});
Classes 	
class BankAccount {
  balance = 0;
  deposit(credit: number) {
     this.balance += credit;
     return this.balance;      var BankAccount = (function () {
  }                              function BankAccount() {
} 	
                               this.balance = 0;
                                 }
                                 BankAccount.prototype.deposit =
                                 function(credit) {
                                   this.balance += credit;
                                   return this.balance;
                                 };
                                 return BankAccount;
                               })();
Modules 	

module M {
  var s = "hello";
  export function f() {
     return s;
  }
}

M.f();
M.s; // Error, s is not exported
TypeScript to JavaScript
interface Person {
   firstname: string;
   lastname: string;
}

function greeter(person : Person) {
   return "Hello, " + person.firstname + " " + person.lastname;
}

var user = {firstname: "Jane", lastname: "User"};

document.body.innerHTML = greeter(user);




function greeter(person) {
   return "Hello, " + person.firstname + " " + person.lastname;
}
var user = {
   firstname: "Jane",
   lastname: "User"
};
document.body.innerHTML = greeter(user);
class Greeter {
  greeting: string;
  constructor ( message: String ) {
    this.greeting = message;
  }
  greet () {
    return “Hello, “ + this.greeting ;
  }
}
var greeter =new Greeter("world");




var Greeter=( function() {
 function Greeter(message){
   this.greeting=message;
 ]
 Greeter.prototype.greet = function(){
   return “Hello, “ + this.greeting ;
 };
   return Greeter:
}) ();
var greeter = new Greeter("world");
class Student {
   fullname : string;
   constructor(public firstname, public middleinitial, public lastname) {
       this.fullname = firstname + " " + middleinitial + " " + lastname;
   }
}

interface Person {
   firstname: string;
   lastname: string;
}

function greeter(person : Person) {
   return "Hello, " + person.firstname + " " + person.lastname;
}

var user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);
var Student = (function () {
   function Student(firstname, middleinitial, lastname) {
      this.firstname = firstname;
      this.middleinitial = middleinitial;
      this.lastname = lastname;
      this.fullname = firstname + " " + middleinitial + " " + lastname;
   }
   return Student;
})();
function greeter(person) {
   return "Hello, " + person.firstname + " " + person.lastname;
}
var user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
module Sayings {
   export class Greeter {
      greeting: string;
      constructor (message: string) {
         this.greeting = message;
      }
      greet() {
         return "Hello, " + this.greeting;
      }
   }
}
var greeter = new Sayings.Greeter("world");

var button = document.createElement('button')
button.innerText = "Say Hello"
button.onclick = function() {
    alert(greeter.greet())
}

document.body.appendChild(button)
var Sayings;
(function (Sayings) {
   var Greeter = (function () {
      function Greeter(message) {
         this.greeting = message;
      }
      Greeter.prototype.greet = function () {
         return "Hello, " + this.greeting;
      };
      return Greeter;
   })();
   Sayings.Greeter = Greeter;
})(Sayings || (Sayings = {}));
var greeter = new Sayings.Greeter("world");
var button = document.createElement('button');
button.innerText = "Say Hello";
button.onclick = function () {
   alert(greeter.greet());
};
document.body.appendChild(button);
class Animal {
   constructor(public name) { }
   move(meters) {
      alert(this.name + " moved " + meters + "m.");
   }
}

class Snake extends Animal {
    constructor(name) { super(name); }
    move() {
      alert("Slithering...");
      super.move(5);
    }
}
var __extends = this.__extends || function (d, b) {
   function __() { this.constructor = d; }
   __.prototype = b.prototype;
   d.prototype = new __();
};
var Animal = (function () {
   function Animal(name) {
      this.name = name;
   }
   Animal.prototype.move = function (meters) {
      alert(this.name + " moved " + meters + "m.");
   };
   return Animal;
})();
var Snake = (function (_super) {
   __extends(Snake, _super);
   function Snake(name) {
      _super.call(this, name);
   }
   Snake.prototype.move = function () {
      alert("Slithering...");
      _super.prototype.move.call(this, 5);
   };
   return Snake;
// Create an alternate method and assign it to only one String variable
function fake_rep(n) {
  return "repeat " + this + n + " times."
}

s1.rep = fake_rep

document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times."
document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb"
document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc”
あらためて、
JavaScriptの進化について	

  もちろん、DartとTypeScriptだけが、JavaScriptの
  進化の未来形ではないだろう。これからも、これまで
  のJavaScriptは、残り続けるだろうし、強力な草の根
  のJavaScriptコミュニティの中から、新しい進化が生
  まれる可能性は、きっとあると思う。
  いずれにしても、プラグラム言語の進化の様々な動き
  の中心の一つが、JavaScriptになることは、間違い
  ないと思う。
資料編	

        End of the World
資料目次	
o  JavaScript
  n  ECMAScript Language Specification 3rd
  n  ECMAScript Language Specification 5th
  n  Javascript Territory – Jster Javascript
      Catalog
  n  List of languages that compile to JS
o  About Node.js
  n    src/node.cc
  n    deps/uv/include/uv.h
  n    deps/uv/src/unix/loop.c
  n    What Server Side JavaScript needs
資料目次	
o  Intel RiverTrail
o  Dart
   n  Dart: A modern web language
   n  Dart Frequently Asked Questions
ECMAScript Language
Specification	


  ECMA-262
  3rd Edition / December 1999
  http://www.ecma-international.org/
  publications/files/ECMA-ST-ARCH/
  ECMA-262,%203rd%20edition,
  %20December%201999.pdf
Overview	
o  ECMAScript is an object-oriented
    programming language for performing
    computations and manipulating
    computational objects within a host
    environment.
o  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.
Web Scripting	
o  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.
Server Side	
o  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.
    By using browser-side and server-side
    scripting together, it is possible to
    distribute computation between the
    client and server while providing a
    customised user interface for a Web-
    based application.
Language Overview	
o  ECMAScript is object-based: basic
    language and host facilities are provided
    by objects, and an ECMAScript program
    is a cluster of communicating objects
o  ECMAScript also defines a set of built-in
    operators that may not be, strictly
    speaking, functions or methods.
Object	
o  ECMAScript does not contain proper
    classes such as those in C++, Smalltalk,
    or Java, but rather, supports
    constructors which create objects by
    executing code that allocates storage for
    the objects and initialises all or part of
    them by assigning initial values to their
    properties. All constructors are objects,
    but not all objects are constructors.
Prototype	
o  Each constructor has a Prototype
    property that is used to implement
    prototype-based inheritance and shared
    properties.
o  ECMAScript supports prototype-based
    inheritance. Every constructor has an
    associated prototype, and every object
    created by that constructor has an
    implicit reference to the prototype
    (called the object’s prototype)
    associated with its constructor.
ECMAScript Language
Specification	


  ECMA-262
  5.1 Edition / June 2011
  http://www.ecma-international.org/
  publications/files/ECMA-ST/
  Ecma-262.pdf
Overview	
o  ECMAScript is an object-oriented
    programming language for performing
    computations and manipulating
    computational objects within a host
    environment.
o  ECMAScript was originally designed to
    be a Web scripting language, providing a
    mechanism to enliven Web pages in
    browsers and to perform server
    computation as part of a Web-based
    client-server architecture.
Web Scripting	
o  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.
o  Further, the host environment provides
    a means to attach scripting code to
    events such as change of focus, page
    and image loading, unloading, ...
Language Overview	
o  ECMAScript is object-based: basic
    language and host facilities are provided
    by objects, and an ECMAScript program
    is a cluster of communicating objects.
o  a function is a callable object. A function
    that is associated with an object via a
    property is a method.
Objects	
o  Each constructor is a function that has a
    property named ―”prototype” that is
    used to implement prototype-based
    inheritance and shared properties.
o  Objects are created by using
    constructors in new expressions;
Prototype	
o  Every object created by a constructor
    has an implicit reference (called the
    object‘s prototype) to the value of its
    constructor‘s ―”prototype” property.
o  Furthermore, a prototype may have a
    non-null implicit reference to its
    prototype, and so on; this is called the
    prototype chain
Prototype	
o  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.
o  In other words, first the object mentioned
    directly is examined for such a property; if that
    object contains the named property, that is the
    property to which the reference refers; if that
    object does not contain the named property,
    the prototype for that object is examined next;
    and so on.
Object/Prototype Relationships
Class-based / Prototype-based	
o  In a class-based object-oriented
    language, in general, state is carried by
    instances, methods are carried by
    classes, and inheritance is only of
    structure and behaviour.
o  In ECMAScript, the state and methods
    are carried by objects, and structure,
    behaviour, and state are all inherited.
Prototype	
o  Property. Defines a property that is
    shared by all objects of the specified
    type.
o  Syntax
    objectType.prototype.propertyName = value
o  Parameters
    n  objectType is the name of a constructor or
        function specifying an object type.
    n  propertyName is the name of the property
        to be created.
    n  value is the property value initially assigned
        for all objects of the specified objectType.
Description	
o  Use the prototype property to explicitly add
    properties to objects created with the new
    operator.
o  For example, you can create Date objects by
    using the Date() constructor and the new
    operator. Date.prototype refers to the
    prototype object for the Date() constructor. If
    you set a property for the prototype, such as
    Date.prototype.description, then all objects
    created with Date() will have the description
    property, even if the objects already exist.
Example	
var today = new Date()
var birthday = new Date(95,12,17)
Date.prototype.description=null
today.description="Oh what a beautiful
mornin'"
birthday.description="The day you were
born”
startDate=new Date()
startDate.description=“Started the daily
grind”
Example 1: Add a property to a
 user-defined object. 	
function Car(make, model, year) {
  this.make = make
  this.model = model
  this.year = year
}

var myCar = new Car("Acura", "Integra", 1987)
Car.prototype.wheels = 4  // no 3-wheelers please!

if (myCar.wheels == 4)
   document.write("The car myCar has ",
                   myCar.wheels, " wheels.”)
Example 2: Add a method to
 String objects.	
var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")

// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
  var s = "", t = this.toString()
  while (--n >= 0) s += t
  return s
}
String.prototype.rep = str_rep

// Display the results
document.write("<P>s1.rep(3) is " + s1.rep(3))  // "aaa"
document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb"
document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”
function Greeter(greeting) {
   this.greeting = greeting;
}
Greeter.prototype.greet = function () {
   return "Hello, " + this.greeting;
};
var greeter = new Greeter("world");

var button = document.createElement('button');
button.innerText = "Say Hello";
button.onclick = function () {
   alert(greeter.greet());
};
document.body.appendChild(button);
Javascript Territory –
Jster Javascript Catalog	


   http://jster.net/
958種のライブラリー !!
JavaScriptライブラリーの種類	
o  Essentials
o  UI
o  Multimedia
o  Graphics
o  Data
o  Development
o  Utilities
o  Applications
Essentials	
o  Application Frameworks (37)
o  Mobile Frameworks (17)
o  MVC Frameworks (27)
o  Realtime Frameworks (4)
o  Desktop GUI (3)
o  ServerSide Libraries (9)
o  Testing Frameworks (55)
o  Templating Engines (20)
o  Loaders (32)
UI	
o  UI Frameworks (21)
o  Windows, Modals, Popups (21)
o  Keyboard Wrappers (25)
o  Form Widgets (52)
o  UI Components (14)
o  Sliders & Galleries (38)
o  Notifications (12)
o  WYSIWYG Editors (30)
o  Touch (51)
Multimedia	
o  Game Engines (77)
o  Physics Libraries (12)
o  Animation Libraries (15)
o  Audio Libraries (17)
o  Presentation Libraries (19)
o  Video Players (9)
Graphics	
o  Canvas Wrappers (16)
o  WebGL (13)
o  Image Manipulation (12)
o  Visualization Libraries (38)
o  Color Libraries (9)
o  Mapping Libraries (9)
Data	
o  Data Structures (19)
o  Date Libraries (9)
o  ORM (3)
o  Storage Libraries (16)
o  Strings (5)
Development	
o  Timing (3)
o  Toolkits (12)
o  Code Protection (15)
o  Language Compilers (16)
o  Debugging Tools (7)
o  Documentation Tools (12)
o  Build Utilities (5)
Utilities	
o  Async, Control Flow, Event (25)
o  Class System (16)
o  DOM (7)
o  Functional Programming (17)
o  Math Libraries (12)
o  Routing (8)
o  Selector Libraries (6)
Applications	
o  Html5 Applications (10)
o  Code Editors (23)
  
List of languages that
compile to JS	


   https://github.com/jashkenas/coffee-
   script/wiki/List-of-languages-that-
   compile-to-JS
List of languages
that compile to JS 200種類以上	
o  CoffeeScript Family (& Friends)
o  JavaScript Extensions
  n  Security enforcing JavaScript
  n  Static typing
  n  Synchronous to Asynchronous JavaScript
      Compilers (CPS)
  n  JavaScript Language Extensions
o  Ruby, Python, Perl, Java/JVM, Scala,
    C# .NET, Lisp Schema, OCaml, Haskell,
    Smalltalk, C/C++. Basic, Pascal, Go
    https://github.com/jashkenas/coffee-script/wiki/
    List-of-languages-that-compile-to-JS
o  MultiTarget
o  Tierless languages (produce both client
    & server)
o  Visual programming tools
o  Others
o  Tools for Compiler Writers
  n    JavaScript Parsers and Extensions
  n    Javascript Optimizers
  n    Javascript Parser Generators
  n    Javascript AST, Semantics
About Node.js	


  Node's goal is to provide an easy way
  to build scalable network programs
  http://nodejs.org/about/
o  In the "hello world" web server example
    below, many client connections can be
    handled concurrently. Node tells the
    operating system (through epoll,
    kqueue, /dev/poll, or select) that it
    should be notified when a new
    connection is made, and then it goes to
    sleep. If someone new connects, then it
    executes the callback. Each connection
    is only a small heap allocation.
var http = require('http');
http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello Worldn');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Node is similar in design to and influenced by
systems like Ruby's Event Machine or Python's
Twisted. Node takes the event model a bit further
—it presents the event loop as a language
construct instead of as a library. In other systems
there is always a blocking call to start the event-
loop. Typically one defines behavior through
callbacks at the beginning of a script and at the
end starts a server through a blocking call like
EventMachine::run(). In Node there is no such
start-the-event-loop call. Node simply enters the
event loop after executing the input script. Node
exits the event loop when there are no more
callbacks to perform. This behavior is like browser
javascript—the event loop is hidden from the user.
But what about multiple-
processor concurrency? 	
Aren't threads necessary to scale programs
to multi-core computers? You can start
new processes via child_process.fork()
these other processes will be scheduled in
parallel. For load balancing incoming
connections across multiple processes use
the cluster module.
Class: ChildProcess	
o  ChildProcess is an EventEmitter.
o  Child processes always have three streams
    associated with them. child.stdin, child.stdout,
    and child.stderr. These may be shared with the
    stdio streams of the parent process, or they
    may be separate stream objects which can be
    piped to and from.
o  The ChildProcess class is not intended to be
    used directly. Use the spawn() or fork()
    methods to create a Child Process instance.
child.send(message,
[sendHandle])	
var cp = require('child_process');
var n = cp.fork(__dirname + '/sub.js');
n.on('message', function(m) {
 console.log('PARENT got message:', m);
});
n.send({ hello: 'world' });


process.on('message', function(m) {
 console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });
src/node.cc
int Start(int argc, char *argv[]) {
  // Hack aroung with the argv pointer. Used for process.title = "blah".
  argv = uv_setup_args(argc, argv);

     // Logic to duplicate argv as Init() modifies arguments
     // that are passed into it.
     char **argv_copy = copy_argv(argc, argv);

     // This needs to run *before* V8::Initialize()
     // Use copy here as to not modify the original argv:
     Init(argc, argv_copy);
	
     V8::Initialize();
     {
       Locker locker;
       HandleScope handle_scope;

      // Create the one and only Context.
      Persistent<Context> context = Context::New();
      Context::Scope context_scope(context);

      process_symbol = NODE_PSYMBOL("process");
      domain_symbol = NODE_PSYMBOL("domain");
// Use original argv, as we're just copying values out of it.
  Handle<Object> process_l = SetupProcessObject(argc, argv);
  v8_typed_array::AttachBindings(context->Global());

  // Create all the objects, load modules, do everything.
  // so your next reading stop should be node::Load()!
  Load(process_l);

  // All our arguments are loaded. We've evaluated all of the scripts. We
  // might even have created TCP servers.
  // Now we enter the main eventloop.
  // If there are no watchers on the loop (except for the ones that were
  // uv_unref'd) then this function exits. As long as there are active
  // watchers, it blocks.
  uv_run(uv_default_loop());

  EmitExit(process_l);
  RunAtExit();

#ifndef NDEBUG
   context.Dispose();
#endif
 }
#ifndef NDEBUG
 // Clean up. Not strictly necessary.
 V8::Dispose();
#endif // NDEBUG

 // Clean up the copy:
 free(argv_copy);

   return 0;
}
deps/uv/include/uv.h
/*
 * This function must be called before any other functions in libuv.
 *
 * All functions besides uv_run() are non-blocking.
 *
 * All callbacks in libuv are made asynchronously. That is they are never
 * made by the function that takes them as a parameter.
 */
UV_EXTERN uv_loop_t* uv_loop_new(void);
UV_EXTERN void uv_loop_delete(uv_loop_t*);

/*
 * Returns the default loop.
 */
UV_EXTERN uv_loop_t* uv_default_loop(void);

/*
 * This function starts the event loop. It blocks until the reference count
 * of the loop drops to zero. Always returns zero.
 */
UV_EXTERN int uv_run(uv_loop_t*);
deps/uv/src/unix/loop.c
int uv__loop_init(uv_loop_t* loop, int default_loop) {
#if HAVE_KQUEUE
  int flags = EVBACKEND_KQUEUE;
#else
  int flags = EVFLAG_AUTO;
#endif

 memset(loop, 0, sizeof(*loop));

 RB_INIT(&loop->ares_handles);
 RB_INIT(&loop->timer_handles);
 ngx_queue_init(&loop->active_reqs);
 ngx_queue_init(&loop->idle_handles);
 ngx_queue_init(&loop->async_handles);
 ngx_queue_init(&loop->check_handles);
 ngx_queue_init(&loop->prepare_handles);
 ngx_queue_init(&loop->handle_queue);
 loop->closing_handles = NULL;
 loop->channel = NULL;
 loop->time = uv_hrtime() / 1000000;
 loop->async_pipefd[0] = -1;
 loop->async_pipefd[1] = -1;
loop->ev = (default_loop ? ev_default_loop : ev_loop_new)(flags);
  ev_set_userdata(loop->ev, loop);
  eio_channel_init(&loop->uv_eio_channel, loop);

#if __linux__
 loop->inotify_watchers = NULL;
 loop->inotify_fd = -1;
#endif
#if HAVE_PORTS_FS
 loop->fs_fd = -1;
#endif
 return 0;
}
CommonJS	


  What Server Side JavaScript needs
  by Kevin Dangoor
  http://www.blueskyonmars.com/
  2009/01/29/what-server-side-javascript-
  needs/
What Server Side JavaScript
needs by Kevin Dangoor	
o  Server side JavaScript technology has
    been around for a long time. Netscape
    offered server side JavaScript in their
    server software back in 1996, and
    Helma has existed for a number of years
    as well. But, server side development
    has changed a lot over the past few
    years.
cross-interpreter standard
library	
o  For example, JavaScript needs a cross-
    interpreter standard library.
    Thankfully, some amount of standard
    library exists (the part inherited from
    the browsers). So, you get regular
    expressions and dates. But, what about
    files and directories? Why can’t the
    same API be made to work in Rhino,
    Spidermonkey, V8 and JSCore?
standard way to include other
modules	
o  JavaScript needs a standard way to
    include other modules and for those
    modules to live in discreet namespaces.
    There are easy ways to do namespaces,
    but there’s no standard programmatic
    way to load a module (once!). This is
    really important, because server side
    apps can include a lot of code and will
    likely mix and match parts that meet
    those standard interfaces.
package up code for
deployment and distribution	
o  There needs to be a way to package up
    code for deployment and distribution
    and further to install packages. Linux
    people will correctly point out that they
    can just type “apt get” (or yum, or
    whatever) and their work is done. But
    there are a lot of people using Macs and
    Windows who need a convenient way to
    get their development environments set up
    and to package up the code they write for
    deployment and for other people to use.
package repository	
o  Part of the distribution and installation
    problem is a package repository. I
    don’t know if JSAN is the answer there,
    but I do know that an easy way to install
    a package and its dependencies
    makes a huge difference in how many
    libraries people will likely pull together in
    their apps.
Intel RiverTrail	


   https://github.com/rivertrail/
   rivertrail/wiki
RiverTrail 	
o  Stephan Herhut
    Richard L. Hudson
    Jaswanth Sreeram
o  2011年9月 IDF 2011で発表
Presented by Justin Rattner, in IDF 2011
Background	
o  The goal of Intel Lab’s River Trail project
    is to enable data-parallelism in web
    applications. In a world where the web
    browser is the user’s window into
    computing, browser applications must
    leverage all available computing
    resources to provide the best possible
    user experience.
Background	
o  Today web applications do not take full
    advantage of parallel client hardware
    due to the lack of appropriate
    programming models. 	
o  River Trail puts the parallel compute
    power of client’s hardware into the
    hands of the web developer while
    staying within the safe and secure
    boundaries of the familiar JavaScript
    programming paradigm.
Background	
o  River Trail gently extends JavaScript
    with simple deterministic data-parallel
    constructs that are translated at runtime
    into a low-level hardware abstraction
    layer. By leveraging multiple CPU cores
    and vector instructions, River Trail
    achieves significant speedup over
    sequential JavaScript.
API Design
Three Pillar Approach	
o  a type called ParallelArray that holds
    data values
o  several prototypical methods of
    ParallelArray that implement parallel
    constructs like map
o  the concept of an elemental function
    which is passed to the constructs and
    typically returns a single data element.
ParallelArray Data Structure	
o  We add ParallelArray, a new data type,
    to JavaScript. It is a read only data
    structure holding the actual Parallel
    Array data that is created by a call to a
    constructor or is returned from a call to
    one of the ParallelArray prototype
    methods. Input to the constructor is
    typically a JavaScript array, a typed
    array, or a function that is used to
    generate the ParallelArray’s values.
Prototype Methods	
o  ParallelArray comes with the following 5
    data parallel methods: map, combine,
    scan, filter, and scatter. Each of these
    methods when combined with kernel
    functions creates new freshly minted
    ParallelArray.
o  ParallelArray sixth core data parallel
    method is reduce which can return a
    scalar value.
Elemental Functions	
o  Any JavaScript function with an
    appropriate signature can be used as an
    elemental function. It is the
    responsibility of the system to
    determine if the elemental function can
    be optimized to take advantage of the
    data parallel hardware. If optimization is
    not possible the function is simple
    executed sequentially.
Dart:
A modern web language	


  Kasper Lund
  http://www.infoq.com/presentations/
  Dart-A-Modern-Web-Language
The rise of JavaScript
Why is the web hard to
program for?	
o  Writing large well-performing
    applications is hard
o  Hard to reason about the program
    structure
o  Startup performance is often really bad
o  Difficult to document intent (lack of
    types)
o  No support for modules, packages, or
    libraries
So why are we building Dart?	
o  We want to improve the web platform
  n  Better support for programming in the large
  n  Faster application startup in particular on
      mobile
  n  More predictable and better runtime
      performance
  n  JavaScript is a powerful tool but it has sharp
      edges
o  Keep up the innovation momentum
  n  The web is evolving at a fantastic pace!
  n  The developer tools have to keep up
JavaScript is full of ... surprises	
o  Lots and lots of implicit type conversions
o  Most operations produce weird results
    when passed wrong or uninitialized
    values instead of failing in a
    recognizable way	




             Keep on truckin'
No argument type checking
var x = 42;
assert(x + null == 42);
assert(x + [] == 42);
assert(isNaN(x + undefined));
assert(isNaN(x - {}));

No array bounds checking
var array = new Array(32);
...
assert(array[32] === undefined);
assert(array[-1] === undefined);
assert(array[.1] === undefined);
assert(array[null] === undefined);
assert(array[array] === undefined);
JavaScript has improved but ...	
o  JavaScript has fundamental issues at the
    language level that impact productivity
o  Performance has improved but mostly
    for a pretty static subset of JavaScript
o  It remains very time consuming to build
    and maintain large web apps
What is Dart?	
o  Unsurprising object-oriented
    programming language
o  Class-based single inheritance with
    interfaces
o  Familiar syntax with proper lexical
    scoping
o  Single-threaded with isolate-based
    concurrency
o  Optional static types
Conventional type checking	
o  Tries to prove that your program obeys
    the type system
o  Considers it a fatal error no proof can be
    constructed
o  In Dart, you are innocent until proven
    guilty...	
    List<Apple> apples = tree.pickApples();
    printFruits(apples);
    void printFruits(List<Fruit> fruits) {
        for (Fruit each in fruits) print(each);
    }
Optional static types	
o  Static types convey the intent of the
    programmer
o  Checkable documentation for code and
    interfaces
o  Avoids awkward variable naming or
    comment schemes
o  Type annotations have no effect on
    runtime semantics.
Dart virtual machine	
o  Dart has been designed for performance
  n  Simplicity gives more performance
      headroom
  n  Enforced structure leads to better
      predictability
  n  Virtual machine performs better than V8 at
      launch
o  Works standalone or embedded in
    browser
  n  Experimental Dart-enabled build of
      Chromium
  n  SDK includes preliminary server-side librarie
Snapshots	
o  Snapshots contain serialized program
    structures
  n  Cyclic graph of classes, interfaces, and
      statics
  n  Can be read in without parsing source code
  n  improve startup performance by more than
      10x
o  Snapshots can be generated server-side
    or client-side
  n  Platform independent format sent over the
      wire
  n  Can be cached locally in browser app cache
Dart-to-JavaScript	
o  Compiler is implemented in Dart
  n  Generates JavaScript that runs in modern
      browsers
  n  Built for future optimizations (type
      inferencing, etc.)
  n  Uses tree shaking to cut down on code size
Dart
Frequently Asked Questions 	


  http://www.dartlang.org/support/
  faq.html#why-dart
Dart
Frequently Asked Questions 	


  http://www.dartlang.org/support/
  faq.html#why-dart
Why Dart?	
o  At Google we've written our share of
    web apps, and we've tried in many ways
    to make improvements to that
    development process, short of
    introducing a new language. Now we
    think it's time to take that leap. We
    designed Dart to be easy to write
    development tools for, well-suited to
    modern app development, and capable
    of high-performance implementations.
Is the language really what needs to
be fixed in web development?	
o  We want to fix ALL the things. There's "Dart"
    the language, and then there's "Dart" the
    overall project. The Dart project is betting that
    the language needs some changes, but we also
    want to improve the DOM and other libraries,
    and to improve the tools we use.
o  At the same time, Google is also placing bets
    that JavaScript can be evolved as needed, and
    contributing to that work. Google wants web
    development to be great, and if that happens
    with JavaScript, we're happy.
Is Dart going to divert community
effort from JavaScript-based web
development?	
o  If people like Dart and use it, then to a certain
    extent, yes, but isn't this true of any
    improvement to existing web development?
    Nothing is zero-effort to learn or 100% back-
    compatible to legacy browsers, so people use
    both new and old. You might look at it this
    way: Google is putting significant effort behind
    both Dart and JavaScript, choosing to develop
    Dart while at the same time using JavaScript
    extensively, and working on JavaScript tools,
    implementation, and language spec. We're
    doing both because we think Dart is worth it.
o  Server-side web programming finds room for
    many languages: does Python divert effort
    from Perl, and does Java undercut C++?
    Again, to a certain extent, yes they do, but
    people generally consider that a healthy
    situation, better than if we all used a
    single programming language. Multiple
    languages have allowed for faster change than
    any single language has achieved through a
    standards process. Furthermore, languages
    coexist in different niches: does Groovy really
    compete directly with C++? People face
    different engineering tradeoffs and choose
    different languages to meet them. Ultimately,
    we think client-side developers should have
    this kind of flexibility.
Why didn't Google make Dart an
open standard right from the start?	
o  We're taking the usual route to get to an open-
    standard programming language: someone
    creates a coherent first version, people
    experiment with it, and we standardize later.
    The open standard web platform has been
    known to add other pieces this way, where
    standardization follows after a vendor
    experiment: canvas, for example. We
    understand that this route raises concerns, but
    we think it is sometimes useful, and in
    particular that it is useful for programming
    languages, where design by committee is
    risky.
o  The most recent successful language
    designed by an open committee was
    Haskell, starting in 1990. The most
    widely used was COBOL, followed by
    Ada. It's not a common way to do
    language design. Among dozens and
    dozens of major languages, six (give or
    take a couple of debatables) were
    designed this way. (And one of those six
    was ALGOL-68.)
Java scriptの進化
Java scriptの進化

More Related Content

What's hot

JVM のいろはにほ #javajo
JVM のいろはにほ #javajoJVM のいろはにほ #javajo
JVM のいろはにほ #javajoYuji Kubota
 
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaTomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaNorito Agetsuma
 
Java開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyJava開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyYasuharu Nakano
 
Jvm言語とJava、切っても切れないその関係
Jvm言語とJava、切っても切れないその関係Jvm言語とJava、切っても切れないその関係
Jvm言語とJava、切っても切れないその関係yy yank
 
Groovy Bootcamp 2015 by JGGUG
Groovy Bootcamp 2015 by JGGUGGroovy Bootcamp 2015 by JGGUG
Groovy Bootcamp 2015 by JGGUGUehara Junji
 
JVMの中身を可視化してみた
JVMの中身を可視化してみたJVMの中身を可視化してみた
JVMの中身を可視化してみたKengo Toda
 
Groovy Shell Scripting 2015
Groovy Shell Scripting 2015Groovy Shell Scripting 2015
Groovy Shell Scripting 2015Uehara Junji
 
JSX 速さの秘密 - 高速なJavaScriptを書く方法
JSX 速さの秘密 - 高速なJavaScriptを書く方法JSX 速さの秘密 - 高速なJavaScriptを書く方法
JSX 速さの秘密 - 高速なJavaScriptを書く方法Kazuho Oku
 
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)Koichi Sakata
 
SignalRブートキャンプ
SignalRブートキャンプSignalRブートキャンプ
SignalRブートキャンプKouji Matsui
 
OpenJDK トラブルシューティング #javacasual
OpenJDK トラブルシューティング #javacasualOpenJDK トラブルシューティング #javacasual
OpenJDK トラブルシューティング #javacasualYuji Kubota
 
WebAssemblyのWeb以外のことぜんぶ話す
WebAssemblyのWeb以外のことぜんぶ話すWebAssemblyのWeb以外のことぜんぶ話す
WebAssemblyのWeb以外のことぜんぶ話すTakaya Saeki
 
モダンJavaScript環境構築一歩目
モダンJavaScript環境構築一歩目モダンJavaScript環境構築一歩目
モダンJavaScript環境構築一歩目大樹 小倉
 
東京Node学園 今できる通信高速化にトライしてみた
東京Node学園 今できる通信高速化にトライしてみた東京Node学園 今できる通信高速化にトライしてみた
東京Node学園 今できる通信高速化にトライしてみたYoshiki Shibukawa
 
Unified JVM Logging
Unified JVM LoggingUnified JVM Logging
Unified JVM LoggingYuji Kubota
 
Javascriptのあれやこれやをまとめて説明してみる
Javascriptのあれやこれやをまとめて説明してみるJavascriptのあれやこれやをまとめて説明してみる
Javascriptのあれやこれやをまとめて説明してみるShunji Konishi
 
Chunked encoding を使った高速化の考察
Chunked encoding を使った高速化の考察Chunked encoding を使った高速化の考察
Chunked encoding を使った高速化の考察Yoshiki Shibukawa
 
RUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践SmalltalkRUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践SmalltalkSho Yoshida
 
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみましたYahoo!デベロッパーネットワーク
 

What's hot (20)

JVM のいろはにほ #javajo
JVM のいろはにほ #javajoJVM のいろはにほ #javajo
JVM のいろはにほ #javajo
 
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷JavaTomcatの実装から学ぶクラスローダリーク #渋谷Java
Tomcatの実装から学ぶクラスローダリーク #渋谷Java
 
Java開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovyJava開発の強力な相棒として今すぐ使えるGroovy
Java開発の強力な相棒として今すぐ使えるGroovy
 
Jvm言語とJava、切っても切れないその関係
Jvm言語とJava、切っても切れないその関係Jvm言語とJava、切っても切れないその関係
Jvm言語とJava、切っても切れないその関係
 
Groovy Bootcamp 2015 by JGGUG
Groovy Bootcamp 2015 by JGGUGGroovy Bootcamp 2015 by JGGUG
Groovy Bootcamp 2015 by JGGUG
 
.NET vNext
.NET vNext.NET vNext
.NET vNext
 
JVMの中身を可視化してみた
JVMの中身を可視化してみたJVMの中身を可視化してみた
JVMの中身を可視化してみた
 
Groovy Shell Scripting 2015
Groovy Shell Scripting 2015Groovy Shell Scripting 2015
Groovy Shell Scripting 2015
 
JSX 速さの秘密 - 高速なJavaScriptを書く方法
JSX 速さの秘密 - 高速なJavaScriptを書く方法JSX 速さの秘密 - 高速なJavaScriptを書く方法
JSX 速さの秘密 - 高速なJavaScriptを書く方法
 
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)
Guide to GraalVM (Oracle Groundbreakers APAC 2019 Tour in Tokyo)
 
SignalRブートキャンプ
SignalRブートキャンプSignalRブートキャンプ
SignalRブートキャンプ
 
OpenJDK トラブルシューティング #javacasual
OpenJDK トラブルシューティング #javacasualOpenJDK トラブルシューティング #javacasual
OpenJDK トラブルシューティング #javacasual
 
WebAssemblyのWeb以外のことぜんぶ話す
WebAssemblyのWeb以外のことぜんぶ話すWebAssemblyのWeb以外のことぜんぶ話す
WebAssemblyのWeb以外のことぜんぶ話す
 
モダンJavaScript環境構築一歩目
モダンJavaScript環境構築一歩目モダンJavaScript環境構築一歩目
モダンJavaScript環境構築一歩目
 
東京Node学園 今できる通信高速化にトライしてみた
東京Node学園 今できる通信高速化にトライしてみた東京Node学園 今できる通信高速化にトライしてみた
東京Node学園 今できる通信高速化にトライしてみた
 
Unified JVM Logging
Unified JVM LoggingUnified JVM Logging
Unified JVM Logging
 
Javascriptのあれやこれやをまとめて説明してみる
Javascriptのあれやこれやをまとめて説明してみるJavascriptのあれやこれやをまとめて説明してみる
Javascriptのあれやこれやをまとめて説明してみる
 
Chunked encoding を使った高速化の考察
Chunked encoding を使った高速化の考察Chunked encoding を使った高速化の考察
Chunked encoding を使った高速化の考察
 
RUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践SmalltalkRUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践Smalltalk
 
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました
#jjug_ccc #ccc_f1 広告システム刷新の舞台裏 - PHPからJavaに変えてみました
 

Similar to Java scriptの進化

Web App Framework at SwapSkills vol28
Web App Framework at SwapSkills vol28Web App Framework at SwapSkills vol28
Web App Framework at SwapSkills vol28光一 原田
 
One ASP.NET の今とこれから
One ASP.NET の今とこれからOne ASP.NET の今とこれから
One ASP.NET の今とこれからAkira Inoue
 
マイクロソフトWeb開発の今と今後
マイクロソフトWeb開発の今と今後マイクロソフトWeb開発の今と今後
マイクロソフトWeb開発の今と今後Akira Inoue
 
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~Akira Inoue
 
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!Akira Inoue
 
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説Akira Inoue
 
Google Compute EngineとPipe API
Google Compute EngineとPipe APIGoogle Compute EngineとPipe API
Google Compute EngineとPipe APImaruyama097
 
Google Compute EngineとGAE Pipeline API
Google Compute EngineとGAE Pipeline APIGoogle Compute EngineとGAE Pipeline API
Google Compute EngineとGAE Pipeline APImaruyama097
 
Web制作勉強会 #2
Web制作勉強会 #2Web制作勉強会 #2
Web制作勉強会 #2Moto Yan
 
.NET の過去、現在、そして未来 ~ .NET 最新アップデート
.NET の過去、現在、そして未来 ~ .NET 最新アップデート.NET の過去、現在、そして未来 ~ .NET 最新アップデート
.NET の過去、現在、そして未来 ~ .NET 最新アップデートAkira Inoue
 
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力Akira Inoue
 
JavaScript And Keywords
JavaScript And KeywordsJavaScript And Keywords
JavaScript And Keywordsuupaa
 
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考えるNetラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考えるdavid9142
 
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指してAkira Inoue
 
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~Akira Inoue
 
試して学べるクラウド技術! OpenShift
試して学べるクラウド技術! OpenShift試して学べるクラウド技術! OpenShift
試して学べるクラウド技術! OpenShiftEtsuji Nakai
 
Concentrated HTML5 & Attractive HTML5
Concentrated HTML5 & Attractive HTML5Concentrated HTML5 & Attractive HTML5
Concentrated HTML5 & Attractive HTML5Sho Ito
 
Getting started with node.js
Getting started with node.jsGetting started with node.js
Getting started with node.jskouzouman
 

Similar to Java scriptの進化 (20)

Web App Framework at SwapSkills vol28
Web App Framework at SwapSkills vol28Web App Framework at SwapSkills vol28
Web App Framework at SwapSkills vol28
 
One ASP.NET の今とこれから
One ASP.NET の今とこれからOne ASP.NET の今とこれから
One ASP.NET の今とこれから
 
マイクロソフトWeb開発の今と今後
マイクロソフトWeb開発の今と今後マイクロソフトWeb開発の今と今後
マイクロソフトWeb開発の今と今後
 
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~
Linux & Mac OS でも動く! ~ オープンソース & クロスプラットフォーム .NET の歩き方 ~
 
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!
Cloud から IoT まで、なんでもおまかせ ~ .NET 5 正式リリース!
 
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説
ASP.NET 新時代に向けて ~ ASP.NET 5 / Visual Studio 2015 基礎解説
 
Google Compute EngineとPipe API
Google Compute EngineとPipe APIGoogle Compute EngineとPipe API
Google Compute EngineとPipe API
 
Google Compute EngineとGAE Pipeline API
Google Compute EngineとGAE Pipeline APIGoogle Compute EngineとGAE Pipeline API
Google Compute EngineとGAE Pipeline API
 
Web制作勉強会 #2
Web制作勉強会 #2Web制作勉強会 #2
Web制作勉強会 #2
 
.NET の過去、現在、そして未来 ~ .NET 最新アップデート
.NET の過去、現在、そして未来 ~ .NET 最新アップデート.NET の過去、現在、そして未来 ~ .NET 最新アップデート
.NET の過去、現在、そして未来 ~ .NET 最新アップデート
 
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力
Visual Studio 2012 と ASP.NET に見る、最新 Web 開発の魅力
 
JSX
JSXJSX
JSX
 
JavaScript And Keywords
JavaScript And KeywordsJavaScript And Keywords
JavaScript And Keywords
 
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考えるNetラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
Netラボ2012年6月勉強会 マイクロソフトのオープンソース戦略を考える
 
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して
.NET の今と未来 ~ デバイス&クラウド ネイティブを目指して
 
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~
One ASP.NET ~ 今、ASP.NET に何が起こっているのか? ~
 
試して学べるクラウド技術! OpenShift
試して学べるクラウド技術! OpenShift試して学べるクラウド技術! OpenShift
試して学べるクラウド技術! OpenShift
 
Concentrated HTML5 & Attractive HTML5
Concentrated HTML5 & Attractive HTML5Concentrated HTML5 & Attractive HTML5
Concentrated HTML5 & Attractive HTML5
 
Getting started with node.js
Getting started with node.jsGetting started with node.js
Getting started with node.js
 
Mvc conf session_5_isami
Mvc conf session_5_isamiMvc conf session_5_isami
Mvc conf session_5_isami
 

More from maruyama097

Convolutionl Neural Network 入門
Convolutionl Neural Network 入門Convolutionl Neural Network 入門
Convolutionl Neural Network 入門maruyama097
 
ContainerとName Space Isolation
ContainerとName Space IsolationContainerとName Space Isolation
ContainerとName Space Isolationmaruyama097
 
ニューラル・ネットワークと技術革新の展望
ニューラル・ネットワークと技術革新の展望ニューラル・ネットワークと技術革新の展望
ニューラル・ネットワークと技術革新の展望maruyama097
 
TensorFlowとCNTK
TensorFlowとCNTKTensorFlowとCNTK
TensorFlowとCNTKmaruyama097
 
Neural Network + Tensorflow 入門講座
Neural Network + Tensorflow 入門講座Neural Network + Tensorflow 入門講座
Neural Network + Tensorflow 入門講座maruyama097
 
機械学習技術の現在+TensolFlow White Paper
機械学習技術の現在+TensolFlow White Paper機械学習技術の現在+TensolFlow White Paper
機械学習技術の現在+TensolFlow White Papermaruyama097
 
Cloud OSの進化を考える
Cloud OSの進化を考えるCloud OSの進化を考える
Cloud OSの進化を考えるmaruyama097
 
機械学習技術の現在
機械学習技術の現在機械学習技術の現在
機械学習技術の現在maruyama097
 
大規模分散システムの現在 -- Twitter
大規模分散システムの現在 -- Twitter大規模分散システムの現在 -- Twitter
大規模分散システムの現在 -- Twittermaruyama097
 
Facebook Parseの世界
Facebook Parseの世界Facebook Parseの世界
Facebook Parseの世界maruyama097
 
Project Araとものづくりの未来
Project Araとものづくりの未来Project Araとものづくりの未来
Project Araとものづくりの未来maruyama097
 
ハードウェア技術の動向 2015/02/02
ハードウェア技術の動向 2015/02/02ハードウェア技術の動向 2015/02/02
ハードウェア技術の動向 2015/02/02maruyama097
 
Project Araと新しいものづくりのエコシステム
  Project Araと新しいものづくりのエコシステム  Project Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステムmaruyama097
 
エンタープライズと機械学習技術
エンタープライズと機械学習技術エンタープライズと機械学習技術
エンタープライズと機械学習技術maruyama097
 
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識maruyama097
 
Cyber-Physical Systems とは何か?
Cyber-Physical Systems とは何か?Cyber-Physical Systems とは何か?
Cyber-Physical Systems とは何か?maruyama097
 
Project Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステムProject Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステムmaruyama097
 
人間の思考、機械の思考
人間の思考、機械の思考人間の思考、機械の思考
人間の思考、機械の思考maruyama097
 
グローバル・ネットワークの成立とネットワーク・マーケット
グローバル・ネットワークの成立とネットワーク・マーケットグローバル・ネットワークの成立とネットワーク・マーケット
グローバル・ネットワークの成立とネットワーク・マーケットmaruyama097
 

More from maruyama097 (20)

Convolutionl Neural Network 入門
Convolutionl Neural Network 入門Convolutionl Neural Network 入門
Convolutionl Neural Network 入門
 
ContainerとName Space Isolation
ContainerとName Space IsolationContainerとName Space Isolation
ContainerとName Space Isolation
 
ニューラル・ネットワークと技術革新の展望
ニューラル・ネットワークと技術革新の展望ニューラル・ネットワークと技術革新の展望
ニューラル・ネットワークと技術革新の展望
 
TensorFlowとCNTK
TensorFlowとCNTKTensorFlowとCNTK
TensorFlowとCNTK
 
Neural Network + Tensorflow 入門講座
Neural Network + Tensorflow 入門講座Neural Network + Tensorflow 入門講座
Neural Network + Tensorflow 入門講座
 
機械学習技術の現在+TensolFlow White Paper
機械学習技術の現在+TensolFlow White Paper機械学習技術の現在+TensolFlow White Paper
機械学習技術の現在+TensolFlow White Paper
 
Cloud OSの進化を考える
Cloud OSの進化を考えるCloud OSの進化を考える
Cloud OSの進化を考える
 
機械学習技術の現在
機械学習技術の現在機械学習技術の現在
機械学習技術の現在
 
大規模分散システムの現在 -- Twitter
大規模分散システムの現在 -- Twitter大規模分散システムの現在 -- Twitter
大規模分散システムの現在 -- Twitter
 
Facebook Parseの世界
Facebook Parseの世界Facebook Parseの世界
Facebook Parseの世界
 
Aurora
AuroraAurora
Aurora
 
Project Araとものづくりの未来
Project Araとものづくりの未来Project Araとものづくりの未来
Project Araとものづくりの未来
 
ハードウェア技術の動向 2015/02/02
ハードウェア技術の動向 2015/02/02ハードウェア技術の動向 2015/02/02
ハードウェア技術の動向 2015/02/02
 
Project Araと新しいものづくりのエコシステム
  Project Araと新しいものづくりのエコシステム  Project Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステム
 
エンタープライズと機械学習技術
エンタープライズと機械学習技術エンタープライズと機械学習技術
エンタープライズと機械学習技術
 
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識
人間に出来ること --- 人間 vs 機械 Part I 進化と自然認識
 
Cyber-Physical Systems とは何か?
Cyber-Physical Systems とは何か?Cyber-Physical Systems とは何か?
Cyber-Physical Systems とは何か?
 
Project Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステムProject Araと新しいものづくりのエコシステム
Project Araと新しいものづくりのエコシステム
 
人間の思考、機械の思考
人間の思考、機械の思考人間の思考、機械の思考
人間の思考、機械の思考
 
グローバル・ネットワークの成立とネットワーク・マーケット
グローバル・ネットワークの成立とネットワーク・マーケットグローバル・ネットワークの成立とネットワーク・マーケット
グローバル・ネットワークの成立とネットワーク・マーケット
 

Java scriptの進化

  • 2. Agenda I 進化の概観 o  I-1 JavaScriptの適用範囲の拡大 n  ブラウザー・サーバー内言語としての誕生 n  jQueryの成功 -- WebのAJAX世代 n  HTML5への期待の拡大 n  Node.js -- クライアントからサーバーへ n  JavaScriptの繁栄 o  I-2 JavaScriptの言語機能の拡大 n  Intel RiverTrail – Multi-Coreへの対応 n  Google Dart – 新しいWeb言語の提案 n  Microsoft TypeScript – 新しい標準?
  • 3. Agenda II 言語としての進化 o  II-1 JavaScriptの言語としての本来の特徴 n  ホスト環境内言語 n  オブジェクト指向:Prototype-Based Inheritance n  関数型言語 o  II-2 JavaScript言語の進化 n  jQuery -- 非同期・関数型の展開 n  Node.jsの飛躍 -- ホスト環境からの脱却 n  RiverTrail -- ParallelArrayパターン n  Dartの問題提起 -- JavaScriptはScaleしない n  TypeScriptの目指すもの
  • 4. “Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons.” --- JavaScript Wikipedia
  • 5. “Java is a blue collar language. It’s not PhD thesis material but a language for a job. Java feels very familiar to many different programmers because we preferred tried-and-tested things.” --- “The Feel of Java” James Gosling IEEE Computer, June 1997
  • 6. “Much of the relative simplicity of Java is — like for most new languages—partly an illusion and partly a function of its incompleteness. As time passes, Java will grow significantly in size and complexity. It will double or triple in size and grow implementation-dependent extensions or libraries.” — Bjarne Stroustrup, ≤ 2/97
  • 7. Part I 進化の概観 細かな技術的な議論に入る前に、大雑把に、 JavaScriptの発展を、現象として概観しよう。 最初に、その領域の拡大の歴史をみておこう。 そして、最近、活発に行われている、言語機 能の強化の動きをみることにしよう。
  • 8. 進化の概観 JavaScriptの適用範囲の拡大 p  ブラウザー・サーバー内言語としての誕生 p  jQueryの成功 -- WebのAJAX世代 p  HTML5への期待の拡大 p  Node.js -- クライアントからサーバーへ p  JavaScriptの繁栄
  • 9. Webブラウザー・ Webサーバー内言語としての誕生 JavaScriptは、1995年、NetScapeのブラ ウザー内の言語として生まれた。 indeed, there are no provisions in this specification for input of external data or output of computed results. ECMA 262 3rd
  • 10. JavaScriptの誕生 o  Author Brendan Eich o  1994年 Mocha, LiveScript o  1995年 12月4日 プレスリリース o  1996年 3月 Version 1.0 on NetScape 2.0 o  1996年 8月 Version 1.1 on NetScape 3.0 o  1998年 10月 1.3 ECMA-262 1st + 2nd o  2000年 11月 1.4 ECMA-262 3rd o  2010年  7月 1.8.5 ECMA-262 5th
  • 12. jQueryの成功 -- WebのAJAX世代 JavaScriptの大きな成功は、AJAXの登場に よってもたらされた。それはまた、jQueryの 成功と、ほぼ重なっていた。 jQuery is designed to change the way that you write JavaScript.
  • 13. jQuery o  Author John Resig now led by Dave Methvin o  2006年1月 at BarCamp NYC o  1.0 August 26, 2006 o  1.1 January 14, 2007   ... ... o  1.8.0 August 9, 2012 o  1.8.3 November 13, 2012 o  1.9.0 early 2013 o  2.0 early 2013
  • 14.
  • 15. JavaScript Library 利用状況 o  jQuery 91% o  Prototype 13% o  Modernizr 58% o  Ext.js 11% o  underscore.js o  MooTools 10%           33% o  KnockoutJS 10% o  backbone.js 30% o  Sencha Touch o  Raphael.js 19% 10% o  YUI 15% o  AngularJS 8% o  Google Closure o  Ember 6% 15% o  Dojo 6% o  Zepto 13% o  Kendo UI 4%
  • 16. HTML5への期待の拡大 JavaScriptへの期待は、新しいWeb標準で あるHTML5への期待によって、更に、拡大し てきた。JavaScriptは、Webの世界の標準 言語としての地位を確立しつつある。
  • 17. HTML5 o  2008 - First Public Working Draft o  2011 - Last Call o  2012 - Working Draft o  Plan 2014
  • 18. W3C HTML5 Multi Media HTML5 Forms HTML5 Parser Mouse Key ev. Offline Support XHTML WAI ARIA Semantic Element Mozilla浅井さんの資料、”Pure Web Apps”より。 http://www.slideshare.net/dynamis
  • 19. WHATWG HTML Canvas Web Messaging Web Socket Server Setn Evnt Web Storage Web Workers Micro Data
  • 22.
  • 23. Node.js   -- クライアントからサーバーへ Node.jsは、JavaScriptの適応範囲をサー バーへと広げた。それは、JavaScriptのブラ ウザー内言語からの脱却を意味している。 Node's goal is to provide an easy way to build scalable network programs
  • 24. Node.js o  Author Ryan Dahl o  2009年5月 v0.0.1 o  2009年11月 JSConf EUで発表 o  2009.06.11, Version 0.0.3 (GitHub) o  2010.08.20, Version 0.2.0 o  2011.02.10, Version 0.4.0 o  2011.11.04, Version 0.6.0 o  2012.06.25, Version 0.8.0 ... ... o  2012.10.24, Version 0.9.3 (Unstable)
  • 25.
  • 26. CommonJS o  January 2009: "ServerJS" Kevin Dangoor o  March 2009: CommonJS API 0.1 o  April 2009: JSConf in Washington, DC. o  August 2009: The group name was formally changed to “CommonJS”
  • 27. JavaScriptの繁栄 JavaScriptは、現在、大きな繁栄の時期を迎 えている。言語のスピードは、ネーティブに迫 るほど早くなり、無数のライブラリーが生まれ ている。
  • 31. List of languages that compile to JS 200種類以上 o  CoffeeScript Family (& Friends) o  JavaScript Extensions n  Security enforcing JavaScript n  Static typing n  Synchronous to Asynchronous JavaScript Compilers (CPS) n  JavaScript Language Extensions o  Ruby, Python, Perl, Java/JVM, Scala, C# .NET, Lisp Schema, OCaml, Haskell, Smalltalk, C/C++. Basic, Pascal, Go https://github.com/jashkenas/coffee-script/wiki/ List-of-languages-that-compile-to-JS
  • 32. 進化の概観 JavaScriptの言語機能の拡大 p  Intel RiverTrail – Multi-Coreへの対応 p  Google Dart – 新しいWeb言語の提案 p  Microsoft TypeScript – 新しい標準?
  • 33. Intel RiverTrail -- Multi-Coreへの対応 RiverTrailは、デバイスのマルチコアのパ ワーをブラウザーで活用することを目的とした JavaScriptの拡張である。 https://github.com/rivertrail/rivertrail/wiki
  • 34. RiverTrail o  Stephan Herhut Richard L. Hudson Jaswanth Sreeram o  2011年9月 IDF 2011で発表
  • 35. Presented by Justin Rattner, in IDF 2011
  • 36. Google Dart – 新しいWeb言語の提案 Dartは、Googleによる、JavaScriptに代わる 新しいWeb言語の提唱である。 Dart brings structure to web app engineering with a new language, libraries, and tools. http://www.dartlang.org
  • 37. Dart o  Lars Bak Kasper Lund Seth Ladd Eli Brandt ... o  2011年10月 GOTO Conferenceで発表
  • 38.
  • 40. Microsoft TypeScript -- 新しい標準? TypeScriptは、新しいJavaScriptの標準で あるECMA6を意識した、Microsoftによる、 JavaScriptの拡張の試みである。 Starts from JavaScript, Ends with JavaScript
  • 41. TypeScript o  Anders Hejlsberg Steve Lucco Luke Hoban ... o  2012年10月1日 発表
  • 42.
  • 43. Part II 言語としての進化 ここでは、まず、JavaScriptが言語として、本 来持っていたいくつかの特質に注目しよう。 ついで、先に概観した言語の発展の歴史の節 目が、こうした特質についての言語としての進 化の節目でもあることを確認する。
  • 44. JavaScriptの 言語としての本来の特徴 p  ホスト環境内言語 p  オブジェクト指向:Prototype-Based Inheritance p  関数型言語
  • 45. JavaScriptの 言語としての本来の特徴 p  ホスト環境内言語 Node.jsでの見直し p  オブジェクト指向:Prototype-Based Inheritance    TypeScriptでの発展 p  関数型言語  jQuery,Node.jsでの展開
  • 46. ECMA 262 6th? o  ECMAScript is a vibrant language and the evolution of the language is not complete. Significant technical enhancement will continue with future editions of this specification.
  • 48. ホスト環境内言語 ブラウザー内のWeb記述言語 o  当初は、Webブラウザーだけではなく、Webサーバーで も動くことが期待されていた。 o  実際には、Webブラウザー内で動く、Web記述言語とし て、いわば、ブラウザーとの共生関係の下で、ブラウザー とともに発展してきた。Webブラウザーが、JavaScriptの 環境を提供している。 o  Webアプリのフレームワークが想定しているように、Web ブラウザーが、アプリの唯一のユーザー・インターフェース であるならば、それは言語としては、さほど大きな制限に ならない。 o  同時に、Thin Server Architectureのような、Webアプ リのフレームワーク以外でも、ブラウザーは、クライアント のプレゼンテーション層の担い手として重要である。
  • 49. Core JavaScript Guide October 30, 1998 Version 1.4 o  JavaScript is Netscape’s cross-platform, object-oriented scripting language. o  JavaScript is a small, lightweight language; it is not useful as a standalone language, but is designed for easy embedding in other products and applications, such as web browsers. Inside a host environment, JavaScript can be connected to the objects of its environment to provide programmatic control over them.
  • 50. ホスト環境内言語 ECMA 262 3rd o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. o  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. o  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.
  • 51. Web記述言語 ECMA 262 5th o  前ページの一項と同じ記述 o  ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture. o  前ページの二項と同じ記述 o  Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image loading, unloading, ...
  • 52. ブラウザーAPIが提供する JavaScriptの実行環境 o  Document Object Model (DOM) n  ページ内のDocumentを、nodeの木構造/親子関係 で表現したもの n  nodeは、オブジェクトでpropertyを持つ o  Browser Object Model (BOM) n  ブラウザーをコントロールするオブジェクト群 n  frame, history, location, XMLHttpRequest 等 o  JavaScript objects and functions n  JavaScriptは、DOM, BOMへのアクセスを可能にす る言語。 n  それ自身のオブジェクト、関数を持つ
  • 53. ブラウザーAPIが提供する JavaScriptの実行環境 document.body.style. backgroundColor = 'red’; location.replace('newpage.html'); http://javascript.info/files/tutorial/browser/JSTop.png
  • 54. ブラウザーのEvent Loopの利用 o  JavaScriptは、ブラウザーの一つのWindowに対応した 1スレッド上で実行される。それゆえ、JavaScriptは、ス レッド操作命令を持たない。 o  JavaScript上のイベントは、ブラウザーのEvent Loop / Event queueでハンドルされる。 o  基本的には、イベントのCallback関数を、ブラウザーの Event queueに積み込んでいく。ブラウザーのEvent Loopが、定期的にEvent queueをチェックする。 o  ブラウザー内言語としての、この特別な特徴は、jQuery で全面的に利用され、ブラウザー内言語からの脱却であ るnode.jsのアーキテクチャに、直接的な影響を与えた。
  • 55. オブジェクト指向: Prototype-Based Inheritance JavaScriptのオブジェクト指向の特徴である、 prototypeの利用は、ごく早い時期から、 NetScape Navigator 3.0上の、JavaScript 1.1から、実装されている。
  • 56. JavaScript 1.1 HandBook http://web.archive.org/web/20020611210350/ http://wp.netscape.com/eng/mozilla/3.0/handbook/ javascript/index.html
  • 57. オブジェクト指向: Prototype-Based Inheritance o  Each constructor has a Prototype property that is used to implement prototype-based inheritance and shared properties. ECMAScript 3rd o  Each constructor is a function that has a property named ―”prototype” that is used to implement prototype-based inheritance and shared properties. ECMAScript 5th
  • 58. Prototype o  Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ―”prototype” property. o  Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain
  • 60. Example var today = new Date() var birthday = new Date(95,12,17) Date.prototype.description=null today.description="Oh what a beautiful mornin'" birthday.description="The day you were born” startDate=new Date() startDate.description=“Started the daily grind”
  • 61. Example 1: Add a property to a user-defined object. function Car(make, model, year) { this.make = make this.model = model this.year = year } var myCar = new Car("Acura", "Integra", 1987) Car.prototype.wheels = 4 // no 3-wheelers please! if (myCar.wheels == 4) document.write("The car myCar has ", myCar.wheels, " wheels.”)
  • 62. Example 2: Add a method to String objects. var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa" document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb" document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”
  • 63. Prototype.js Class.create() -- Obsolete var Person = Class.create(); Person.prototype = { initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }; var guy = new Person('Miro'); guy.say('hi'); // -> "Miro: hi”
  • 64. Prototype.js Object.extend() -- Obsolete var Pirate = Class.create(); // inherit from Person class: Pirate.prototype = Object.extend(new Person(), { // redefine the speak method say: function(message) { return this.name + ': ' + message + ', yarr!'; } }); var john = new Pirate('Long John'); john.say('ahoy matey'); // -> "Long John: ahoy matey, yarr!"
  • 65. Prototype.js Class.create() – New! // properties are directly passed to `create` method var Person = Class.create({ initialize: function(name) { this.name = name; }, say: function(message) { return this.name + ': ' + message; } }); // when subclassing, specify the class you want to inherit from var Pirate = Class.create(Person, { // redefine the speak method say: function($super, message) { return $super(message) + ', yarr!'; } });
  • 66. Prototype.js Class.create() Mixin – New! var Vulnerable = { wound: function(hp) { this.health -= hp; if (this.health < 0) this.kill(); }, kill: function() { this.dead = true; } }; // the first argument isn't a class object, so there is no inheritance ... // simply mix in all the arguments as methods: var Person = Class.create(Vulnerable, { initialize: function() { this.health = 100; this.dead = false; } });
  • 67. TypeScript Class ==> JavaScript class BankAccount { balance = 0; deposit(credit: number) { this.balance += credit; return this.balance; } var BankAccount = (function () { } function BankAccount() { this.balance = 0; } BankAccount.prototype.deposit = function(credit) { this.balance += credit; return this.balance; }; return BankAccount; })();
  • 68. Dart Class ==> JavaScript class Point { var x, y; Point(this.x, this.y); toString() => "($x,$y)”; } Dartは、prototypeを使っていない Isolate.$defineClass("Point", "Object", ["x", "y"], { toString$0: function() { return '(' + $.toString(this.x) + ',' + $.toString(this.y) + ')’; } });
  • 69. オブジェクト指向言語としての JavaScript o  現時点で、JavaScriptの言語としての進化の、 一つの焦点になっているのが、大規模開発を意 識した、JavaScriptのオブジェクト指向言語とし ての機能強化である。 o  JavaScriptの発展を目指すTypeScriptも、 JavaScriptの対抗言語となることも辞さない Dartも、このことを強く意識している。 o  ただ、確認しておきたいことは、JavaScriptが本 来持っていた、prototypeベースのオブジェクト 指向が、極めて柔軟で強力なオブジェクト指向の 枠組みを提供しているということである。
  • 70. 関数型言語としてのJavaScript prototypeと同様に、functionは、言語のご く初期から、JavaScript 1.1から導入された。
  • 71. オブジェクト指向 Class型とPrototype型 o  Class型のJavaでは、クラスは、フィールドとメ ソッドによって定義され、クラスのインスタンスとし てのオブジェクトは、基本的にフィールドの値で特 徴付けられる。 o  Prototype型のJavaScriptのオブジェクトは、そ れが持つプロパティのオブジェクトによって定義さ れる。JavaScriptでは、フィールドとメソッドの区 別は、相対的なものである。 o  重要なのは、JavaScriptでは、functionもオブ ジェクトであり、プロパティの値になること。
  • 72. JavaScript 1.1 HandBook http://web.archive.org/web/20020611210350/ http://wp.netscape.com/eng/mozilla/3.0/handbook/ javascript/index.html
  • 73. Operator, Function o  ECMAScript also defines a set of built-in operators that may not be, strictly speaking, functions or methods.                     ECMAScript 3rd o  a function is a callable object. A function that is associated with an object via a property is a method.                   ECMAScript 5th
  • 74. JavaScriptで、functionは、 第一級の市民 o  JavaScript 1.0では、functionは、operatorと 呼ばれていたようだ。 o  JavaScriptの特徴として、functionが第一級の 市民であることの認識は、当初からあったもので はなく、歴史的に形成されてきたように見える。 o  おそらく、jQueryの非同期のCallbackの実装ス タイルが広く知られたことが、大きな転機になった ように思える。 o  もちろん、Prototype型のオブジェクト指向が、も ともと、それを可能にしていたのではあるが。
  • 75. // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; });
  • 76. 関数型言語としてのJavaScript o  jQuery, node.jsという発展を通じて、関数型言 語としてのJavaScriptの特質は、その進化を牽 引してきた。今日でも、それは、JavaScriptの もっとも魅力的で強力な特徴の一つになっている。 o  オブジェクト指向言語であると同時に、関数型言 語でもあるという、JavaScriptの二つの側面が、 今後、どのように発展していくかは、興味深いもの がある。 o  次回のセミナーでは、関数型言語としての JavaScriptに、あらためて焦点を合わせたいと 考えている。
  • 77. JavaScript言語の進化 p  jQuery -- 非同期・関数型の展開 p  Node.jsの飛躍 -- ホスト環境からの脱却 p  RiverTrail -- ParallelArrayパターン p  Dartの問題提起 -- JavaScriptはScale しない p  TypeScriptの目指すもの
  • 78. jQuery -- 非同期・関数型の展開 jQueryは、Structured Web世代の AJAX(Asynchronous JavaScript + XML)技術を支える代表的なJavaScriptラ イブラリーである。そこではDOMは、HTTPの Request/Responseを待たずに、非同期に 書き換えられる。
  • 79. jQueryとは何か? o  jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. o  jQuery is designed to change the way that you write JavaScript.
  • 83. AJAX用のメソッド o  jQuery.get() n  Load data from the server using a HTTP GET request. o  jQuery.getJSON() n  Load JSON-encoded data from the server using a GET HTTP request. o  jQuery.getScript() n  Load a JavaScript file from the server using a GET HTTP request, then execute it. o  .load() n  Load data from the server and place the returned HTML into the matched element. o  jQuery.post() n  Load data from the server using a HTTP POST request.
  • 84. AJAX Event o  ajaxStart (Global Event) n  beforeSend (Local Event) n  ajaxSend (Global Event) n  success (Local Event) n  ajaxSuccess (Global Event) n  error (Local Event) n  ajaxError (Global Event) n  complete (Local Event) n  ajaxComplete (Global Event) o  ajaxStop (Global Event)
  • 85. jQuery.ajax( url [, settings] ) o  Ajax関連の関数の実装には、関数ajax()が使 われている。 o  この関数は、引数一つだけをとるのだが、次のよ うに、Hashを渡すことで、多数のオプションを指 定出来る。 $.ajax( { url: "script.php", type: "post", success: function(result) { alert(result); } });
  • 86. ajax()のオプションの例 o  async : boolean o  dataType : string o  cache : boolean o  error : function o  complete : o  jsonp : string function o  scriptCharset : o  contentType : string string o  success : function o  data : object, o  timeout : number string o  type : string o  dataFilter : o  url : string function o  xhr : function
  • 87. Ajaxの呼び出し例 <div id = "form"> <input type = "text" id = "name"> <input type = "text" id = "email_address"> <input type = "text" id = "number"> <input type = "submit" onclick = "$.ajax({url:'submit.php' + getform('input', '#form'), type:'post'})"> </div>
  • 88. function getform(input, form) { /* Copyright Greg Sidelnikov - www.learnjquery.org - greg.sidelnikov@gmail.com. You can use it in your own projects, retain this line, if you wish to give me credit. */ var ret = "?"; var Length = $(element, parent).length; var idnamelist = new Array(); var idvaluelist = new Array(); for (var i = 0; i < Length; i++) { idnamelist[i] = $(element, parent)[i].id; idvaluelist[i] = $(element, parent)[i].value; ret = idnamelist[i] + '=' + idvaluelist[i]; if (i < Length - 1) ret += "&"; } }
  • 89. EventHandlerのbind/unbind p  要素に、特定のイベントのEventHandlerを設定 しておくことが出来る。 p  要素上で、そのイベントが発生した特、 EventHandlerが呼び出される。 var handler = function() {    alert(‘ Hello World!'); }; $(’#greet').bind('click', handler); $(’#greet').unbind('click', handler);
  • 90. eventの「名前」と、同名の関数 o  次の二つは、同じ働きをする。  $(window).bind( “load”, function()      { alert('Window finished loading.'); } );  $(window).load( function()      { alert('Window finished loading.'); } );
  • 91. jQueryの特徴 o  jQueryの大きな特徴は、AJAXを、イベント・ドリ ブンで非同期な関数呼び出しのスタイルで実装し たことにある。そこでは、JavaScriptの関数型言 語としての特質が、全面的に利用されている。 o  JavaScriptは、もともと、Single-Threadで走っ ているので、それは、Multi-threadではない、 Single-Thread上の、「並列」処理という、一見 奇妙な形を取る。 o  ただ、こうした、アプローチは、孤立したものでは ない。ErlangやScalaのAkkaも、原理的には同 じアプローチだと言っていい。
  • 92. jQueryの特徴 o  もともと、一つのCPUを取ってみれば、同時には 一つの処理しか行えない。Multi-Process / Multi-Thredといった「並行」処理は、OSのタイ ム・スライスが生み出す、擬似的なものである。 o  その点は、多数のCPUが協調動作する、「分散」 処理の「並列性」とは、別のものである。 o  ブラウザー内言語という性格もあって、jQueryの 疑似並列性は、OSによってではなく、ホスト環境 としてのブラウザーのEvent Loop / Event Queueによって担保されている。
  • 93. Node.jsの飛躍 -- ホスト環境からの脱却 JavaScriptの、この間の言語としての進化で、 最大のものは、Node.jsの登場である。 ブラウザーというホスト環境に依存していた言 語は、そこからの脱却を始める。EventLoop を自分自身で持つことによって。
  • 94. クライアントからサーバーへ? o  今回の講演の前半では、node.jsの登場を、「ク ライアントからサーバーへ」と、JavaScriptの適 応範囲の拡大として、特徴付けた。 o  ただ、node.jsをよく見ていくと、node.jsの登場 を、JavaScriptの側からだけみる、こうした見方 は、いささか狭いものであることに気付く。 o  基本的には、JavaScriptの内部の問題ではなく、 より一般的な、イベント・ドリブンで非同期な入出 力に対する関心の高まりが背景にあることがわ かる。
  • 95. 2009年11月 JSConf Ryan Dahlの登場 o  ここでは、node.jsの爆発的な拡大の起点となった、 2009年ベルリンで行われた、JSConfでのnode.js の創始者Ryan Dahlの講演の一部を見てみよう。 “Node.js, Evented I/O for V8 Javascript” by Ryan Dahl n  http://jsconf.eu/2009/speaker/ speakers_selected.html#entry-3356 n  http://s3.amazonaws.com/four.livejournal/ 20091117/jsconf.pdf
  • 96. I/O は、違ったやり方で 行われる必要がある。 o  多くのWebアプリは、次のようなコードを使う。 var result = db.query("select * from T"); // use result o  データベースを検索している間、ソフトウェアは何 をしているのだろう? たいていの場合、ただレス ポンスを待っているだけである。 o  それに加えて、IOによる遅延は、コンピュータの 能力と比較すると、次のように、巨大なものである。 http://s3.amazonaws.com/four.livejournal/20091117/jsconf.pdf
  • 97. I/O による遅延 l  L1: 3 cycles l  L2: 14 cycles l  RAM: 250 cycles l  DISK: 41,000,000 cycles l  NETWORK: 240,000,000 cycles o  別の例を挙げよう。サーバーのパフォーマンスも 実装によって大きな違いが生まれている。次のズ は、AppacheとNGINXを比較したものである。
  • 98. Apache vs NGINX 違いはどこにあるのか? o  Apache はコネクションあたり一つのスレッドを使っている が、NGINXは、スレッドを使っていない。それは、event loopを使っている。
  • 99. o  コンテキストの切り替えは、ただで出来る訳では ないし、スレッドの実行用のスタックは、メモリーを 食う。大規模な並列処理では、それぞれのコネク ション毎にOSのスレッドを使うことは出来ない。グ リーン・スレッドやコルーティンは、こうした状況を 劇的に改善出来る。 o  しかし、I/Oの実行を維持しているという幻想を生 み出す、入り組んだメカニズムが、依然として存 在している。スレッドによる並列性は、漏れの多い 抽象である。
  • 100. var result = db.query("select.."); o  このようなコードは、全体のプロセスをブロックす るか、複数のプロセスの実行をスタックさせること になるかのいずれかである。 o  しかし、次のようなコードでは、プログラムは、すぐ にevent loopに戻ることが可能である。どのよう なメカニズムも必要としない。 db.query("select..", function (result) { // use result }); o  これが、I/Oが行われるべき方法である。 o  では、何故、誰もがevent loopやCallbackや Non-BlokingI/Oを使わないのだろうか?
  • 101. 文化的偏見 o  我々は、I/Oを次のように行うと教えられてきた 1.  puts("Enter your name: "); 2.  var name = gets(); 3.  puts("Name: " + name); o  我々は、入力を要求されたら、それが終わるまで 何もしないと教えられてきた。次のようなコードは、 複雑すぎるとして、退けられてきた。 1.  puts("Enter your name: "); 2.  gets(function (name) { 3.  puts("Name: " + name); });
  • 102. インフラの不在 o  それでは、何故、誰もが event loopを使わない のだろう? o  シングル・スレッドのevent loopは、I/Oが non- blockingであることを要求するのだが、ほとんど のライブラリーはそうなっていない。 n  POSIX async file I/O は使えない. n  Man pagesは、関数がディスクにアクセスすることが あることを触れていない。 (e.g getpwuid()) n  Cに、クロージャーや無名関数がないことが、コール バックを難しくしている。 n  データベースのライブラリーは(e.g. libmysql)、非同 期のサポートをしていない。
  • 103. JavaScript o  Javascriptは、event loopと一緒に使われるよ うに、特別にデザインされた言語である。 n  無名関数、クロージャー n  同時には、一つだけのコールバック n  DOMのイベントコールバックを通じたI/O o  JavaScriptのカルチャーは、既に、イベント中心 のプログラミングの準備ができている。
  • 105. Design Goals o  No function should direct perform I/O. n  To receive info from disk, network, or another process there must be a callback. o  Low-level. n  Stream everything; never force the buffering of data. n  Do not remove functionality present at the POSIX layer. For example, support half- closed TCP connections. n  Have built-in support for the most important protocols: TCP, DNS, HTTP
  • 106. Design Goals o  Support many HTTP features. n  Chunked requests and responses. n  Keep-alive. n  Hang requests for comet applications. o  The API should be both familiar to client-side JS programmers and old school UNIX hackers. o  Be platform independent.
  • 107. An Introduction to libuv http://nikhilm.github.com/uvbook/An %20Introduction%20to%20libuv.pdf http://vimeo.com/51637038
  • 108. Libuv o  libuv enforces an asynchronous, event- driven style of programming. o  Its core job is to provide an event loop and callback based notifications of I/O and other activities. o  libuv offers core utilities like timers, non-blocking networking support, asynchronous file system access, child processes and more.
  • 109. Event loops o  In event-driven programming, an application expresses interest in certain events and respond to them when they occur. o  The responsibility of gathering events from the operating system or monitoring other sources of events is handled by  libuv, and the user can register callbacks to be invoked when an event occurs. o  The event-loop usually keeps running  forever.
  • 110. #include <stdio.h> #include #include <fcntl.h> <unistd.h> libuvスタイルでの #include <uv.h> catの実装 void on_read(uv_fs_t *req); open, red, writeの uv_fs_t open_req; uv_fs_t read_req; イベントの libuv版は、第一引数に ようなもの uv_fs_t write_req; loopを取る。最終引数は callback char buffer[1024]; void on_write(uv_fs_t *req) { // callbackのsigniture uv_fs_req_cleanup(req); if (req->result < 0) { fprintf(stderr, "Write error: %sn",         uv_strerror(uv_last_error(uv_default_loop()))); } else { uv_fs_read(uv_default_loop(), &read_req, open_req.result,       buffer, sizeof(buffer), -1, on_read); // callback } } // on_write callbackの中で、on_read callbackが呼ばれる
  • 111. void on_read(uv_fs_t *req) { // callbackのsigniture uv_fs_req_cleanup(req); if (req->result < 0) { fprintf(stderr, "Read error: %sn",        uv_strerror(uv_last_error(uv_default_loop()))); } else if (req->result == 0) { uv_fs_t close_req; // synchronous uv_fs_close(uv_default_loop(),            &close_req, open_req.result, NULL); } // callbackがNULL、同期型 else { uv_fs_write(uv_default_loop(),            &write_req, 1, buffer, req->result, -1, on_write); } // callback }  // on_read callbackの中で、on_write callbackが呼ばれる
  • 112. void on_open(uv_fs_t *req) { // callbackのsigniture if (req->result != -1) { uv_fs_read(uv_default_loop(), &read_req, req->result, buffer, sizeof(buffer), -1, on_read); // callback } else { fprintf(stderr, "error opening file: %dn", req->errorno); } uv_fs_req_cleanup(req); } // on_open callbackの中で、on_read callbackが呼ばれる int main(int argc, char **argv) { uv_fs_open(uv_default_loop(),       &open_req, argv[1], O_RDONLY, 0, on_open); // callback return 0; } // openは、on_open callbackを呼んで、すぐループに入る。
  • 113. RiverTrail -- ParallelArray パターン River Trail gently extends JavaScript with simple deterministic data- parallel constructs
  • 114. RiverTailの背景 o  Intel LabのRiverTrailプロジェクトは、Webア プリにおいて、データの並列計算を可能にするも のである。 o  Webブラウザーが、ユーザーのコンピューティン グの窓口になっている世界では、最良のユー ザー・エクスペリエンスを提供するために、ブラウ ザーのアプリケーションは、利用可能な全ての計 算資源の力にてこ入れをしなければならない。
  • 115. API デザイン 三つの柱のアプローチ o  ParallelArray と呼ばれるデータの値を保持 する型 o  mapのような、並列計算を実装した、いくつかの prototypical methodsと呼ばれる ParallelArrayのメソッド o  典型的には、一つのデータ要素を返し、 ParallelArrayのような構成物に渡される elemental function のコンセプト
  • 116. ParallelArray Constructor pa1 = new ParallelArray([ [0,1], [2,3], [4,5] ]); // <<0,1>, <2,3>, <4.5>> pa2 = new ParallelArray(pa1); new ParallelArray(<0,1>, <2,3>); // <<0,1>,<2,3>> new ParallelArray(3, function(i){return [i, i+1];}); // <<0,1><1,2><2,3>> new ParallelArray([3,2], function(iv){return iv[0]*iv[1];}); // <<0,0><0,1><0,4>> new ParallelArray(canvas);
  • 117. Prototype Methods var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.map( function inc(v) { return v+1; }); // <2,3,4,5,6> var source = new ParallelArray([1,2,3,4,5]); var plusOne = source.combine( function inc(i) { return this.get(i)+1; }); // <2,3,4,5,6> var source = new ParallelArray([1,2,3,4,5]); var reverse = source.combine(function rev(i) { return this.get(this.length-i[0]-1); }); // <5,4,3,2,1>
  • 118. Prototype Methods var source = new ParallelArray([1,2,3,4,5]); var sum = source.reduce( function plus(a,b) { return a+b; }); // 15 var source = new ParallelArray([1,2,3,4,5]); var psum = source.scan( function plus(a,b) { return a+b; }); // <1, 3, 6, 10, 15>
  • 119. Prototype Methods var source = new ParallelArray([1,2,3,4,5]); var even = source.filter( function even(iv) { return (this.get(iv) % 2) == 0; }); // <2,4> pa = new ParallelArray([ [1,2], [3,4] ]) // <<1,2>,<3,4>> pa.flatten() // <1,2,3,4>
  • 120. Prototype Methods var source = new ParallelArray([1,2,3,4,5]); var indices = [0, 1, 2, 3, 4]; var identity = source.scatter(indices); // <1, 2, 3, 4, 5> var reorder = source.scatter([4,0,3,1,2]); // <2, 4, 5, 3, 1> // if there is a conflict use the max. // use 33 as a default value. var reorder = source.scatter([4,0,3,4,2], 33, function max(a, b) {return a>b?a:b; }); // <2, 33, 5, 3, 4>
  • 121. プログラマは、どのように 並列アルゴリズムを記述しうるか? o  Multi-core化の進展は、特に、身近なデバイス 上でのその進展は、普通のプログラマにとっても、 並列アルゴリズムの必要性を意識させるきっかけ になるかもしれない。 o  ただ、並列アルゴリズムの実装は、難しい。 ParallelArrayは、プログラマが、容易に並列ア ルゴリズムにアクセス出来るように設計された、 パターンである。 o  Javaの新しいバージョンも、基本的には、同じ ParallelArrayのアプローチを採用している。
  • 122. DartとTypeScript これ以降の節で取り上げる、GoogleのDartと MicrosoftのTypeScriptは、いずれも、JavaScript の開発の大規模化が抱える問題の認識から出発して いる。それはまた、前回のセミナーで取り上げた、 Facebookも共有しているであろう問題意識である。 ただ、JavaScriptに対する両者のスタンスは、異なっ ている。JavaScriptの枠の中での発展を目指す TypeScriptと、JavaScriptの置き換えを目指す Dartという構造になる。
  • 123. Dartの問題提起 -- JavaScriptはScaleしない Dartは、Googleの提案する、新しいWeb言語である。 ブラウザーを中心として対象とする領域は、 JavaScriptと重なっている。基本的には独自のVM上 で動くのだが、JavaScriptに変換するコンパイラーを持 ち、JavaScriptを強く意識している。 なぜ、GoogleはJavaScriptに代わるWeb言語を提案 しているのだろう?
  • 124.
  • 125. 何故、Webはプログラムが難しいのか o  大規模の、きちんと動くアプリを書くのは、大変難しい。 o  プログラムの構造を推察するのが難しい o  立ち上がりのパフォーマンスが、しばしば、非常に悪い。 o  (型がないことによる)意図を文書化することの困難 o  modules, packages, librariesがサポートされていな い。 Dart: Modern Web Language Kasper Lund http://www.infoq.com/presentations/Dart-A-Modern-Web-Language
  • 126. それでは、何故、 我々は、Dartを作ったのか? o  我々は、Webプラットフォームを改善したい n  大規模なプログラミングの、より良いサポート n  とりわけ、モバイルでの迅速なアプリの立ち上げ n  より予測可能で、より良い実行時のパフォーマンス n  JavaScriptは強力なツールではあるが、危険なところ も持っている o  イノベーションの勢いを維持する n  Webは、ファンタスティクなペースで進化し続けている n  開発者のツールは、水準を上げなければならない
  • 127. JavaScriptは、「驚き」に満ちている o  沢山の沢山の、暗黙の型変換 o  間違った、あるいは、初期化しないままで値を渡 したとき、ほとんどの関数は、理解可能な仕方で 失敗するのではなく、とんでもない結果を返してく る。 Keep on truckin’
  • 128. Dart Technical Overview Design Goalから o  小さなスクリプトが、明確な構造を持たないまま、 大規模なWebアプリに発展することがよくあるが、 こうしたアプリは、デバッグも難しいし、メンテする のも難しい。 o  それに加えて、こうしたモノリシックなアプリは、 別々のチームが独立にそのアプリについて仕事 をしようとしても、分割が出来ない。Webアプリが 大きくなるにつれて、生産的であることは難しくな る。
  • 129. o  スクリプト言語が人気があるのは、その軽量な性 格がコードを早く書くことを容易にしているからで ある。一般的に言って、アプリのその他の部分と の契約関係は、言語の構造自身というよりも、コメ ントによってになわれることになる。その結果、あ る特定のコードの一部は、そのコードを書いた本 人以外にとっては、読むこともメンテすることも難 しくなる。 o  既存の言語では、開発者は、静的な言語と動的 な言語の間で選択を迫られる。伝統的な静的言 語では、重たい沢山のツール群と柔軟ではなく束 縛し過ぎと感じられるコーディング・スタイルが要 求されることになる。
  • 130. o  開発者は、これまで、クライアントとサーバーの両 方をまたいだ、均質なシステムを作り出すことが 出来なかった。Node.jsやGoogle Web Toolkit (GWT)といった少数の例外を除いては。 o  異なる言語とフォーマットは、退屈なコンテキスト の切り替えを必然的に伴い、コーディングのプロ セスに複雑さを付け加えている。
  • 131. Technical Overview Key features p  Classes p  Optional types p  Libraries p  Tooling http://www.dartlang.org/docs/ technical-overview/
  • 132. Design goals o  Create a structured yet flexible programming language for the web. o  Make Dart feel familiar and natural to programmers and thus easy to learn. o  Ensure that all Dart language constructs allow high performance and fast application startup. o  Make Dart appropriate for the full range of devices on the web—including phones, tablets, laptops, and servers. o  Provide tools that make Dart run fast across all major modern browsers.
  • 133. interface Shape { num perimeter(); } class Rectangle implements Shape { final num height, width; Rectangle(num this.height, num this.width); // Compact constructor syntax. num perimeter() => 2*height + 2*width; // Short function syntax. } class Square extends Rectangle { Square(num size) : super(size, size); }
  • 134. import 'dart:math'; class Point { var x, y; Point(this.x, this.y); scale(factor) => new Point(x*factor, y*factor); distance() => sqrt(x*x + y*y); } main() { var a = new Point(2,3).scale(10); print(a.distance()); }
  • 135. import 'dart:math'; class Point { num x, y; Point(num this.x, num this.y); Point scale(num factor) => new Point(x*factor, y*factor); num distance() => sqrt(x*x + y*y); } void main() { Point a = new Point(2,3).scale(10); print(a.distance()); }
  • 136. Improving the DOM http://www.dartlang.org/articles/ improving-the-dom/
  • 137. Use real collections Old New o  elem.hasAttribute('na o  elem.attributes.contai me'); nsKey('name'); o  elem.getAttribute('na o  elem.attributes['nam me') e']; o  elem.setAttribute('na o  elem.attributes['nam me', 'value'); e'] = 'value'; o  elem.removeAttribute o  elem.attributes.remo ('name'); ve('name');
  • 138. Use real collections / Use Constructor Old New o  elem.hasChildNodes() o  elem.nodes.isEmpty() ; ; o  elem.firstChild(); o  elem.nodes[0]; o  elem.appendChild(chi o  elem.nodes.add(child ld); ); o  document.createElem o  new DivElement(); ent('div');
  • 139. Events Old New o  elem.addEventListene o  elem.on.click.add( r('click', (event) => (event) => print('click!')); print('click!'), false); o  elem.removeEventLis o  elem.on.click.remove tener( (listener); 'click', listener);
  • 140. Events Old New o  elem.addEventListene o  elem.on['some' + r( 'name'].add( 'some' + 'name', (event) => (event) => print('dynamic!')); print('dynamic!'), false);
  • 141. TypeScriptの目指すもの p  Scalable p  Starts from JavaScript, Ends with JavaScript p  Strong Tools for Large Applications
  • 142. Scalable o  TypeScriptは、頑健なコンポーネント作成を助 ける為に、class, module, interfaceを提供す る。 o  これらの特徴を、高信頼なアプリ開発において、 開発時に利用出来る。ただし、それらは、シンプ ルなJavaScriptにコンパイルされる。 o  TypeScriptの型は、ソフトウェア・コンポーネント 間のインターフェース定義を可能とし、また、既存 のJavaScriptライブラリーの振る舞いの洞察も 得ることが出来る。
  • 143. Starts from JavaScript, Ends with JavaScript o  TypeScriptは、数百万のJavaScript開発者が今日知っ ている、シンタックスとセマンティックスから始まる。 o  TypeScriptでは、 既存のJavaScriptコードを利用する ことが出来るし、よく使われているJavaScriptライブラリと 合体することも出来る。また、他のJavaScriptコードから 呼び出されることも出来る。 o  TypeScriptは、どんなブラウザー上でも、node.jsでも、 どんなES3互換の環境でも動く、クリーンでシンプルな JavaScriptコードにコンパイルされる。
  • 144. Strong Tools for Large Applications o  型は、静的チェック、シンボルベースのナビゲー ション、文の補完、コードのリファクタリングといっ た、高い生産性を持つ開発ツールと実践を、 TypeScript開発者が行うことを可能とする。 o  これらの型は、オプショナルなものである。型推論 は、少数の型のアノテーションでも、コードの静的 な検証に、大きな違いをもたらすことが出来る。
  • 145. 
 TypeScript Language Specification http://www.typescriptlang.org/ Content/TypeScript%20Language %20Specification.pdf
  • 146. Introduction o  TypeScript is a syntactic sugar for JavaScript. TypeScript syntax is a superset of Ecmascript 5 (ES5) syntax. Every JavaScript program is also a TypeScript program. o  TypeScript syntax includes several proposed features of Ecmascript 6 (ES6), including classes and modules. o  TypeScript also provides to JavaScript programmers a system of optional type annotations. These type
  • 147. Introduction o  1.1 Ambient Declarations o  1.2 Function Types o  1.3 Object Types o  1.4 Structural Subtyping o  1.5 Contextual Typing o  1.6 Classes o  1.7 Modules .
  • 148. Ambient Declarations o  An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. o  Programmers can use ambient declarations to tell the TypeScript compiler that some other component will supply a variable declare var document; document.title = "Hello"; // Ok because document has been declared
  • 149. Function Types o  TypeScript function types make it possible for programmers to express the expected signature of a function. function vote(candidate: string,            callback: (result: string) => any)   { // ... } A function type literal of the form    ( ParamList ) => ReturnType is exactly equivalent to the object type literal    { ( ParamList ) : ReturnType }
  • 150. Object Types o  TypeScript programmers use object types to declare their expectations of object behavior. o  The following code uses an object type literal to specify the return type of the ‘MakePoint’ function var MakePoint: () => { x: number; y: number; };
  • 151. Object Types : Interfaces o  Programmers can give names to object types; we call named object types interfaces. o  For example, in the following code, an interface declares one required field (name) and one optional field (favoriteColor). interface Friend { name: string; favoriteColor?: string; }
  • 152. interface Friend { name: string; favoriteColor?: string; } function add(friend: Friend) { var name = friend.name; } add({ name: "Fred" }); // Ok add({ favoriteColor: "blue" }); // Error, name required add({ name: "Jill", favoriteColor: "green" }); // Ok
  • 153. Structural Subtyping o  Object types are compared structurally. o  A class may optionally declare that it implements an interface, so that the compiler will check the declaration for structural compatibility.
  • 154. interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { constructor ( public x: number, public y: number) {} } getX(new CPoint(0, 0)); // Ok, fields match getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok getX({ x: 0 }); // Error: supplied parameter does not match
  • 155. Contextual Typing interface EventObject { x: number; y: number; } interface EventHandlers { mousedown?: (event: EventObject) => void; mouseup?: (event: EventObject) => void; mousemove?: (event: EventObject) => void; } function setEventHandlers(handlers: EventHandlers) { ... } setEventHandlers({ mousedown: e => { startTracking(e.x, e.y); }, mouseup: e => { endTracking(); } });
  • 156. Classes class BankAccount { balance = 0; deposit(credit: number) { this.balance += credit; return this.balance; var BankAccount = (function () { } function BankAccount() { } this.balance = 0; } BankAccount.prototype.deposit = function(credit) { this.balance += credit; return this.balance; }; return BankAccount; })();
  • 157. Modules module M { var s = "hello"; export function f() { return s; } } M.f(); M.s; // Error, s is not exported
  • 159. interface Person { firstname: string; lastname: string; } function greeter(person : Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = {firstname: "Jane", lastname: "User"}; document.body.innerHTML = greeter(user); function greeter(person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = { firstname: "Jane", lastname: "User" }; document.body.innerHTML = greeter(user);
  • 160. class Greeter { greeting: string; constructor ( message: String ) { this.greeting = message; } greet () { return “Hello, “ + this.greeting ; } } var greeter =new Greeter("world"); var Greeter=( function() { function Greeter(message){ this.greeting=message; ] Greeter.prototype.greet = function(){ return “Hello, “ + this.greeting ; }; return Greeter: }) (); var greeter = new Greeter("world");
  • 161. class Student { fullname : string; constructor(public firstname, public middleinitial, public lastname) { this.fullname = firstname + " " + middleinitial + " " + lastname; } } interface Person { firstname: string; lastname: string; } function greeter(person : Person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);
  • 162. var Student = (function () { function Student(firstname, middleinitial, lastname) { this.firstname = firstname; this.middleinitial = middleinitial; this.lastname = lastname; this.fullname = firstname + " " + middleinitial + " " + lastname; } return Student; })(); function greeter(person) { return "Hello, " + person.firstname + " " + person.lastname; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);
  • 163. module Sayings { export class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } } var greeter = new Sayings.Greeter("world"); var button = document.createElement('button') button.innerText = "Say Hello" button.onclick = function() { alert(greeter.greet()) } document.body.appendChild(button)
  • 164. var Sayings; (function (Sayings) { var Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter; })(); Sayings.Greeter = Greeter; })(Sayings || (Sayings = {})); var greeter = new Sayings.Greeter("world"); var button = document.createElement('button'); button.innerText = "Say Hello"; button.onclick = function () { alert(greeter.greet()); }; document.body.appendChild(button);
  • 165. class Animal { constructor(public name) { } move(meters) { alert(this.name + " moved " + meters + "m."); } } class Snake extends Animal { constructor(name) { super(name); } move() { alert("Slithering..."); super.move(5); } }
  • 166. var __extends = this.__extends || function (d, b) { function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var Animal = (function () { function Animal(name) { this.name = name; } Animal.prototype.move = function (meters) { alert(this.name + " moved " + meters + "m."); }; return Animal; })(); var Snake = (function (_super) { __extends(Snake, _super); function Snake(name) { _super.call(this, name); } Snake.prototype.move = function () { alert("Slithering..."); _super.prototype.move.call(this, 5); }; return Snake;
  • 167. // Create an alternate method and assign it to only one String variable function fake_rep(n) { return "repeat " + this + n + " times." } s1.rep = fake_rep document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times." document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb" document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc”
  • 168. あらためて、 JavaScriptの進化について もちろん、DartとTypeScriptだけが、JavaScriptの 進化の未来形ではないだろう。これからも、これまで のJavaScriptは、残り続けるだろうし、強力な草の根 のJavaScriptコミュニティの中から、新しい進化が生 まれる可能性は、きっとあると思う。 いずれにしても、プラグラム言語の進化の様々な動き の中心の一つが、JavaScriptになることは、間違い ないと思う。
  • 169. 資料編 End of the World
  • 170. 資料目次 o  JavaScript n  ECMAScript Language Specification 3rd n  ECMAScript Language Specification 5th n  Javascript Territory – Jster Javascript Catalog n  List of languages that compile to JS o  About Node.js n  src/node.cc n  deps/uv/include/uv.h n  deps/uv/src/unix/loop.c n  What Server Side JavaScript needs
  • 171. 資料目次 o  Intel RiverTrail o  Dart n  Dart: A modern web language n  Dart Frequently Asked Questions
  • 172. ECMAScript Language Specification ECMA-262 3rd Edition / December 1999 http://www.ecma-international.org/ publications/files/ECMA-ST-ARCH/ ECMA-262,%203rd%20edition, %20December%201999.pdf
  • 173. Overview o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. o  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.
  • 174. Web Scripting o  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.
  • 175. Server Side o  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. By using browser-side and server-side scripting together, it is possible to distribute computation between the client and server while providing a customised user interface for a Web- based application.
  • 176. Language Overview o  ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects o  ECMAScript also defines a set of built-in operators that may not be, strictly speaking, functions or methods.
  • 177. Object o  ECMAScript does not contain proper classes such as those in C++, Smalltalk, or Java, but rather, supports constructors which create objects by executing code that allocates storage for the objects and initialises all or part of them by assigning initial values to their properties. All constructors are objects, but not all objects are constructors.
  • 178. Prototype o  Each constructor has a Prototype property that is used to implement prototype-based inheritance and shared properties. o  ECMAScript supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has an implicit reference to the prototype (called the object’s prototype) associated with its constructor.
  • 179. ECMAScript Language Specification ECMA-262 5.1 Edition / June 2011 http://www.ecma-international.org/ publications/files/ECMA-ST/ Ecma-262.pdf
  • 180. Overview o  ECMAScript is an object-oriented programming language for performing computations and manipulating computational objects within a host environment. o  ECMAScript was originally designed to be a Web scripting language, providing a mechanism to enliven Web pages in browsers and to perform server computation as part of a Web-based client-server architecture.
  • 181. Web Scripting o  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. o  Further, the host environment provides a means to attach scripting code to events such as change of focus, page and image loading, unloading, ...
  • 182. Language Overview o  ECMAScript is object-based: basic language and host facilities are provided by objects, and an ECMAScript program is a cluster of communicating objects. o  a function is a callable object. A function that is associated with an object via a property is a method.
  • 183. Objects o  Each constructor is a function that has a property named ―”prototype” that is used to implement prototype-based inheritance and shared properties. o  Objects are created by using constructors in new expressions;
  • 184. Prototype o  Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ―”prototype” property. o  Furthermore, a prototype may have a non-null implicit reference to its prototype, and so on; this is called the prototype chain
  • 185. Prototype o  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. o  In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.
  • 187. Class-based / Prototype-based o  In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behaviour. o  In ECMAScript, the state and methods are carried by objects, and structure, behaviour, and state are all inherited.
  • 188. Prototype o  Property. Defines a property that is shared by all objects of the specified type. o  Syntax objectType.prototype.propertyName = value o  Parameters n  objectType is the name of a constructor or function specifying an object type. n  propertyName is the name of the property to be created. n  value is the property value initially assigned for all objects of the specified objectType.
  • 189. Description o  Use the prototype property to explicitly add properties to objects created with the new operator. o  For example, you can create Date objects by using the Date() constructor and the new operator. Date.prototype refers to the prototype object for the Date() constructor. If you set a property for the prototype, such as Date.prototype.description, then all objects created with Date() will have the description property, even if the objects already exist.
  • 190. Example var today = new Date() var birthday = new Date(95,12,17) Date.prototype.description=null today.description="Oh what a beautiful mornin'" birthday.description="The day you were born” startDate=new Date() startDate.description=“Started the daily grind”
  • 191. Example 1: Add a property to a user-defined object. function Car(make, model, year) { this.make = make this.model = model this.year = year } var myCar = new Car("Acura", "Integra", 1987) Car.prototype.wheels = 4 // no 3-wheelers please! if (myCar.wheels == 4) document.write("The car myCar has ", myCar.wheels, " wheels.”)
  • 192. Example 2: Add a method to String objects. var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa" document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb" document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc”
  • 193. function Greeter(greeting) { this.greeting = greeting; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; var greeter = new Greeter("world"); var button = document.createElement('button'); button.innerText = "Say Hello"; button.onclick = function () { alert(greeter.greet()); }; document.body.appendChild(button);
  • 194. Javascript Territory – Jster Javascript Catalog http://jster.net/
  • 196. JavaScriptライブラリーの種類 o  Essentials o  UI o  Multimedia o  Graphics o  Data o  Development o  Utilities o  Applications
  • 197. Essentials o  Application Frameworks (37) o  Mobile Frameworks (17) o  MVC Frameworks (27) o  Realtime Frameworks (4) o  Desktop GUI (3) o  ServerSide Libraries (9) o  Testing Frameworks (55) o  Templating Engines (20) o  Loaders (32)
  • 198. UI o  UI Frameworks (21) o  Windows, Modals, Popups (21) o  Keyboard Wrappers (25) o  Form Widgets (52) o  UI Components (14) o  Sliders & Galleries (38) o  Notifications (12) o  WYSIWYG Editors (30) o  Touch (51)
  • 199. Multimedia o  Game Engines (77) o  Physics Libraries (12) o  Animation Libraries (15) o  Audio Libraries (17) o  Presentation Libraries (19) o  Video Players (9)
  • 200. Graphics o  Canvas Wrappers (16) o  WebGL (13) o  Image Manipulation (12) o  Visualization Libraries (38) o  Color Libraries (9) o  Mapping Libraries (9)
  • 201. Data o  Data Structures (19) o  Date Libraries (9) o  ORM (3) o  Storage Libraries (16) o  Strings (5)
  • 202. Development o  Timing (3) o  Toolkits (12) o  Code Protection (15) o  Language Compilers (16) o  Debugging Tools (7) o  Documentation Tools (12) o  Build Utilities (5)
  • 203. Utilities o  Async, Control Flow, Event (25) o  Class System (16) o  DOM (7) o  Functional Programming (17) o  Math Libraries (12) o  Routing (8) o  Selector Libraries (6)
  • 204. Applications o  Html5 Applications (10) o  Code Editors (23)   
  • 205. List of languages that compile to JS https://github.com/jashkenas/coffee- script/wiki/List-of-languages-that- compile-to-JS
  • 206. List of languages that compile to JS 200種類以上 o  CoffeeScript Family (& Friends) o  JavaScript Extensions n  Security enforcing JavaScript n  Static typing n  Synchronous to Asynchronous JavaScript Compilers (CPS) n  JavaScript Language Extensions o  Ruby, Python, Perl, Java/JVM, Scala, C# .NET, Lisp Schema, OCaml, Haskell, Smalltalk, C/C++. Basic, Pascal, Go https://github.com/jashkenas/coffee-script/wiki/ List-of-languages-that-compile-to-JS
  • 207. o  MultiTarget o  Tierless languages (produce both client & server) o  Visual programming tools o  Others o  Tools for Compiler Writers n  JavaScript Parsers and Extensions n  Javascript Optimizers n  Javascript Parser Generators n  Javascript AST, Semantics
  • 208. About Node.js Node's goal is to provide an easy way to build scalable network programs http://nodejs.org/about/
  • 209. o  In the "hello world" web server example below, many client connections can be handled concurrently. Node tells the operating system (through epoll, kqueue, /dev/poll, or select) that it should be notified when a new connection is made, and then it goes to sleep. If someone new connects, then it executes the callback. Each connection is only a small heap allocation.
  • 210. var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
  • 211. Node is similar in design to and influenced by systems like Ruby's Event Machine or Python's Twisted. Node takes the event model a bit further —it presents the event loop as a language construct instead of as a library. In other systems there is always a blocking call to start the event- loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blocking call like EventMachine::run(). In Node there is no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there are no more callbacks to perform. This behavior is like browser javascript—the event loop is hidden from the user.
  • 212. But what about multiple- processor concurrency? Aren't threads necessary to scale programs to multi-core computers? You can start new processes via child_process.fork() these other processes will be scheduled in parallel. For load balancing incoming connections across multiple processes use the cluster module.
  • 213. Class: ChildProcess o  ChildProcess is an EventEmitter. o  Child processes always have three streams associated with them. child.stdin, child.stdout, and child.stderr. These may be shared with the stdio streams of the parent process, or they may be separate stream objects which can be piped to and from. o  The ChildProcess class is not intended to be used directly. Use the spawn() or fork() methods to create a Child Process instance.
  • 214. child.send(message, [sendHandle]) var cp = require('child_process'); var n = cp.fork(__dirname + '/sub.js'); n.on('message', function(m) { console.log('PARENT got message:', m); }); n.send({ hello: 'world' }); process.on('message', function(m) { console.log('CHILD got message:', m); }); process.send({ foo: 'bar' });
  • 216. int Start(int argc, char *argv[]) { // Hack aroung with the argv pointer. Used for process.title = "blah". argv = uv_setup_args(argc, argv); // Logic to duplicate argv as Init() modifies arguments // that are passed into it. char **argv_copy = copy_argv(argc, argv); // This needs to run *before* V8::Initialize() // Use copy here as to not modify the original argv: Init(argc, argv_copy); V8::Initialize(); { Locker locker; HandleScope handle_scope; // Create the one and only Context. Persistent<Context> context = Context::New(); Context::Scope context_scope(context); process_symbol = NODE_PSYMBOL("process"); domain_symbol = NODE_PSYMBOL("domain");
  • 217. // Use original argv, as we're just copying values out of it. Handle<Object> process_l = SetupProcessObject(argc, argv); v8_typed_array::AttachBindings(context->Global()); // Create all the objects, load modules, do everything. // so your next reading stop should be node::Load()! Load(process_l); // All our arguments are loaded. We've evaluated all of the scripts. We // might even have created TCP servers. // Now we enter the main eventloop. // If there are no watchers on the loop (except for the ones that were // uv_unref'd) then this function exits. As long as there are active // watchers, it blocks. uv_run(uv_default_loop()); EmitExit(process_l); RunAtExit(); #ifndef NDEBUG context.Dispose(); #endif }
  • 218. #ifndef NDEBUG // Clean up. Not strictly necessary. V8::Dispose(); #endif // NDEBUG // Clean up the copy: free(argv_copy); return 0; }
  • 220. /* * This function must be called before any other functions in libuv. * * All functions besides uv_run() are non-blocking. * * All callbacks in libuv are made asynchronously. That is they are never * made by the function that takes them as a parameter. */ UV_EXTERN uv_loop_t* uv_loop_new(void); UV_EXTERN void uv_loop_delete(uv_loop_t*); /* * Returns the default loop. */ UV_EXTERN uv_loop_t* uv_default_loop(void); /* * This function starts the event loop. It blocks until the reference count * of the loop drops to zero. Always returns zero. */ UV_EXTERN int uv_run(uv_loop_t*);
  • 222. int uv__loop_init(uv_loop_t* loop, int default_loop) { #if HAVE_KQUEUE int flags = EVBACKEND_KQUEUE; #else int flags = EVFLAG_AUTO; #endif memset(loop, 0, sizeof(*loop)); RB_INIT(&loop->ares_handles); RB_INIT(&loop->timer_handles); ngx_queue_init(&loop->active_reqs); ngx_queue_init(&loop->idle_handles); ngx_queue_init(&loop->async_handles); ngx_queue_init(&loop->check_handles); ngx_queue_init(&loop->prepare_handles); ngx_queue_init(&loop->handle_queue); loop->closing_handles = NULL; loop->channel = NULL; loop->time = uv_hrtime() / 1000000; loop->async_pipefd[0] = -1; loop->async_pipefd[1] = -1;
  • 223. loop->ev = (default_loop ? ev_default_loop : ev_loop_new)(flags); ev_set_userdata(loop->ev, loop); eio_channel_init(&loop->uv_eio_channel, loop); #if __linux__ loop->inotify_watchers = NULL; loop->inotify_fd = -1; #endif #if HAVE_PORTS_FS loop->fs_fd = -1; #endif return 0; }
  • 224. CommonJS What Server Side JavaScript needs by Kevin Dangoor http://www.blueskyonmars.com/ 2009/01/29/what-server-side-javascript- needs/
  • 225. What Server Side JavaScript needs by Kevin Dangoor o  Server side JavaScript technology has been around for a long time. Netscape offered server side JavaScript in their server software back in 1996, and Helma has existed for a number of years as well. But, server side development has changed a lot over the past few years.
  • 226. cross-interpreter standard library o  For example, JavaScript needs a cross- interpreter standard library. Thankfully, some amount of standard library exists (the part inherited from the browsers). So, you get regular expressions and dates. But, what about files and directories? Why can’t the same API be made to work in Rhino, Spidermonkey, V8 and JSCore?
  • 227. standard way to include other modules o  JavaScript needs a standard way to include other modules and for those modules to live in discreet namespaces. There are easy ways to do namespaces, but there’s no standard programmatic way to load a module (once!). This is really important, because server side apps can include a lot of code and will likely mix and match parts that meet those standard interfaces.
  • 228. package up code for deployment and distribution o  There needs to be a way to package up code for deployment and distribution and further to install packages. Linux people will correctly point out that they can just type “apt get” (or yum, or whatever) and their work is done. But there are a lot of people using Macs and Windows who need a convenient way to get their development environments set up and to package up the code they write for deployment and for other people to use.
  • 229. package repository o  Part of the distribution and installation problem is a package repository. I don’t know if JSAN is the answer there, but I do know that an easy way to install a package and its dependencies makes a huge difference in how many libraries people will likely pull together in their apps.
  • 230. Intel RiverTrail https://github.com/rivertrail/ rivertrail/wiki
  • 231. RiverTrail o  Stephan Herhut Richard L. Hudson Jaswanth Sreeram o  2011年9月 IDF 2011で発表
  • 232. Presented by Justin Rattner, in IDF 2011
  • 233. Background o  The goal of Intel Lab’s River Trail project is to enable data-parallelism in web applications. In a world where the web browser is the user’s window into computing, browser applications must leverage all available computing resources to provide the best possible user experience.
  • 234. Background o  Today web applications do not take full advantage of parallel client hardware due to the lack of appropriate programming models. o  River Trail puts the parallel compute power of client’s hardware into the hands of the web developer while staying within the safe and secure boundaries of the familiar JavaScript programming paradigm.
  • 235. Background o  River Trail gently extends JavaScript with simple deterministic data-parallel constructs that are translated at runtime into a low-level hardware abstraction layer. By leveraging multiple CPU cores and vector instructions, River Trail achieves significant speedup over sequential JavaScript.
  • 236. API Design Three Pillar Approach o  a type called ParallelArray that holds data values o  several prototypical methods of ParallelArray that implement parallel constructs like map o  the concept of an elemental function which is passed to the constructs and typically returns a single data element.
  • 237. ParallelArray Data Structure o  We add ParallelArray, a new data type, to JavaScript. It is a read only data structure holding the actual Parallel Array data that is created by a call to a constructor or is returned from a call to one of the ParallelArray prototype methods. Input to the constructor is typically a JavaScript array, a typed array, or a function that is used to generate the ParallelArray’s values.
  • 238. Prototype Methods o  ParallelArray comes with the following 5 data parallel methods: map, combine, scan, filter, and scatter. Each of these methods when combined with kernel functions creates new freshly minted ParallelArray. o  ParallelArray sixth core data parallel method is reduce which can return a scalar value.
  • 239. Elemental Functions o  Any JavaScript function with an appropriate signature can be used as an elemental function. It is the responsibility of the system to determine if the elemental function can be optimized to take advantage of the data parallel hardware. If optimization is not possible the function is simple executed sequentially.
  • 240. Dart: A modern web language Kasper Lund http://www.infoq.com/presentations/ Dart-A-Modern-Web-Language
  • 241. The rise of JavaScript
  • 242. Why is the web hard to program for? o  Writing large well-performing applications is hard o  Hard to reason about the program structure o  Startup performance is often really bad o  Difficult to document intent (lack of types) o  No support for modules, packages, or libraries
  • 243. So why are we building Dart? o  We want to improve the web platform n  Better support for programming in the large n  Faster application startup in particular on mobile n  More predictable and better runtime performance n  JavaScript is a powerful tool but it has sharp edges o  Keep up the innovation momentum n  The web is evolving at a fantastic pace! n  The developer tools have to keep up
  • 244. JavaScript is full of ... surprises o  Lots and lots of implicit type conversions o  Most operations produce weird results when passed wrong or uninitialized values instead of failing in a recognizable way Keep on truckin'
  • 245. No argument type checking var x = 42; assert(x + null == 42); assert(x + [] == 42); assert(isNaN(x + undefined)); assert(isNaN(x - {})); No array bounds checking var array = new Array(32); ... assert(array[32] === undefined); assert(array[-1] === undefined); assert(array[.1] === undefined); assert(array[null] === undefined); assert(array[array] === undefined);
  • 246. JavaScript has improved but ... o  JavaScript has fundamental issues at the language level that impact productivity o  Performance has improved but mostly for a pretty static subset of JavaScript o  It remains very time consuming to build and maintain large web apps
  • 247. What is Dart? o  Unsurprising object-oriented programming language o  Class-based single inheritance with interfaces o  Familiar syntax with proper lexical scoping o  Single-threaded with isolate-based concurrency o  Optional static types
  • 248. Conventional type checking o  Tries to prove that your program obeys the type system o  Considers it a fatal error no proof can be constructed o  In Dart, you are innocent until proven guilty... List<Apple> apples = tree.pickApples(); printFruits(apples); void printFruits(List<Fruit> fruits) {     for (Fruit each in fruits) print(each); }
  • 249. Optional static types o  Static types convey the intent of the programmer o  Checkable documentation for code and interfaces o  Avoids awkward variable naming or comment schemes o  Type annotations have no effect on runtime semantics.
  • 250. Dart virtual machine o  Dart has been designed for performance n  Simplicity gives more performance headroom n  Enforced structure leads to better predictability n  Virtual machine performs better than V8 at launch o  Works standalone or embedded in browser n  Experimental Dart-enabled build of Chromium n  SDK includes preliminary server-side librarie
  • 251. Snapshots o  Snapshots contain serialized program structures n  Cyclic graph of classes, interfaces, and statics n  Can be read in without parsing source code n  improve startup performance by more than 10x o  Snapshots can be generated server-side or client-side n  Platform independent format sent over the wire n  Can be cached locally in browser app cache
  • 252. Dart-to-JavaScript o  Compiler is implemented in Dart n  Generates JavaScript that runs in modern browsers n  Built for future optimizations (type inferencing, etc.) n  Uses tree shaking to cut down on code size
  • 253. Dart Frequently Asked Questions http://www.dartlang.org/support/ faq.html#why-dart
  • 254. Dart Frequently Asked Questions http://www.dartlang.org/support/ faq.html#why-dart
  • 255. Why Dart? o  At Google we've written our share of web apps, and we've tried in many ways to make improvements to that development process, short of introducing a new language. Now we think it's time to take that leap. We designed Dart to be easy to write development tools for, well-suited to modern app development, and capable of high-performance implementations.
  • 256. Is the language really what needs to be fixed in web development? o  We want to fix ALL the things. There's "Dart" the language, and then there's "Dart" the overall project. The Dart project is betting that the language needs some changes, but we also want to improve the DOM and other libraries, and to improve the tools we use. o  At the same time, Google is also placing bets that JavaScript can be evolved as needed, and contributing to that work. Google wants web development to be great, and if that happens with JavaScript, we're happy.
  • 257. Is Dart going to divert community effort from JavaScript-based web development? o  If people like Dart and use it, then to a certain extent, yes, but isn't this true of any improvement to existing web development? Nothing is zero-effort to learn or 100% back- compatible to legacy browsers, so people use both new and old. You might look at it this way: Google is putting significant effort behind both Dart and JavaScript, choosing to develop Dart while at the same time using JavaScript extensively, and working on JavaScript tools, implementation, and language spec. We're doing both because we think Dart is worth it.
  • 258. o  Server-side web programming finds room for many languages: does Python divert effort from Perl, and does Java undercut C++? Again, to a certain extent, yes they do, but people generally consider that a healthy situation, better than if we all used a single programming language. Multiple languages have allowed for faster change than any single language has achieved through a standards process. Furthermore, languages coexist in different niches: does Groovy really compete directly with C++? People face different engineering tradeoffs and choose different languages to meet them. Ultimately, we think client-side developers should have this kind of flexibility.
  • 259. Why didn't Google make Dart an open standard right from the start? o  We're taking the usual route to get to an open- standard programming language: someone creates a coherent first version, people experiment with it, and we standardize later. The open standard web platform has been known to add other pieces this way, where standardization follows after a vendor experiment: canvas, for example. We understand that this route raises concerns, but we think it is sometimes useful, and in particular that it is useful for programming languages, where design by committee is risky.
  • 260. o  The most recent successful language designed by an open committee was Haskell, starting in 1990. The most widely used was COBOL, followed by Ada. It's not a common way to do language design. Among dozens and dozens of major languages, six (give or take a couple of debatables) were designed this way. (And one of those six was ALGOL-68.)