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の発展を、現象として概観しよう。
最初に、その領域の拡大の歴史をみておこう。
そして、最近、活発に行われている、言語機
能の強化の動きをみることにしよう。
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
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
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”
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で発表
40. Microsoft TypeScript
-- 新しい標準?
TypeScriptは、新しいJavaScriptの標準で
あるECMA6を意識した、Microsoftによる、
JavaScriptの拡張の試みである。
Starts from JavaScript, Ends with JavaScript
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.
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, ...
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;
}
});
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
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
}); }; });
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.
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 += "&";
}
}
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
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.
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>
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');
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
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
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”
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
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);
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.
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*);
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.
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
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
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.)