JS2
-
Upload
jiang-wu -
Category
Technology
-
view
1.377 -
download
6
description
Transcript of JS2
JS2JS2 = JavaScript*JeffSu
• 我们遇到的问题
1. 复杂的 javascript应用,需要可靠的架构
2. 大量 javascript代码,需要良好的组织性
3. 大量应用与 DOM紧密结合
4. 需要更加容易使用的继承和引用的实现
5. 需要快速高效的 javascript开发平台
6. 易读的代码
• 我们的解决方案
– JS2
• javascript伪代码
• 更加类似 Ruby, Java的 OO语法
• 可通过编译实现多重继承等更多特性
• 基于 HAML的 htmlCache
• 可自定义的 javascript语法实现
使用 JS2
gem install js2
js2 public/javascripts app/js2
js2 -d public/javascripts app/js2
Javascript的类定义• 通过定义 prototype
var MyClass = function () { };
MyClass.prototype = {
member1: "member1",
method1: function () { alert("method1 called"); }
}
直接定义函数体var MyClass = function () {
this.member1 = “member1”;
this.method1 = function () {
alert(“method1 called”);
}
}
Javascript的类定义• 通过一些 javascript 框架
var MyClass = Class.create({
member1: "member1",
method1: function () { alert("method1 called"); }
});
JS2类定义语法class MyClass {
var member1 = "member1”;
function method1 () {
alert("method1 called");
}
}
JS2的类继承class Vehicle { function drive () { alert('drive'); }}class Car extends Vehicle { function drive () { _super(this); alert('with car'); }}
优点• 简洁的语法• 实现了 super
Getters and Setters
•Javascript实现Duck.prototype = {
setColor: function (color) { this.color = color; },
getColor: function () { return this.color; }
};
•JS2实现class Duck {
property color;
}
糅合(Mixins)module Flyable {
function fly () {
alert('Flying!');
}
}
class Bird {
include Flyable;
}
class Duck {
include Flyable;
}
静态方法用于解决类似于唯一实例等问题class Human {
static function getCount () {
return this.count;
}
static function create () {
if (this.count) {
this.count++;
} else {
this.count = 1;
}
return new this();
}
}
闭包var nonScoped = [ ... lots of data .. ];
var submitBtn = new Button();
•无闭包的 javascriptDocument.getElementById(‘submitBtn’).onClick = function () {
submitBtn.click();
}
•Javascript闭包Document.getElementById(‘submitBtn’).onClick = function (submitBtn) {
return function (e) { submitBtn.click();};
}(submitBtn);
•JS2闭包Document.getElementById(‘submitBtn’).onClick = curry (e) with (submitBtn) {
submitBtn.click();
};
foreach语法
•Javascript数组循环for(var i=0,len=array.length,item; (item=array[i]) || i<len; i++) {
……
}
•JS2 foreachforeach (var item in array) {}
foreach (var item:i in array) {}
HTML Cache//--- in uiBuilder.js2.haml
UIBuilder
button(name)
%div.button= "#name#"
//--- in uiBuilder.js2
class UIBuilder {
function getButton (name) {
this.htmlCache.button(name);
}
}
//-- in uiBuilder.js
UIBuilder.prototype = {
htmlCache: {"button": function(name){return "<div class='button'>"+name+"</div>"}}
};
更多特性
• 对 Selenium测试的支持• 可嵌入 HAML
• 不断升级添加中
http://code.google.com/p/js2lang/
JS2 Wiki
谢谢