Syntax
Jeff Su edited this page Sep 15, 2011
·
3 revisions
Classes:
class Person {
function initialize(first, last) {
this.first = first;
this.last = last;
}
function name() {
return this.first + ' ' + this.last;
}
}
class Employee extends Person {
function initialize(first, last, title) {
this.$super(first, last);
this.title = title;
}
function name() {
return this.$super() + ', ' + this.title;
}
}
Modules/Mixins:
module Walkable {
function walk() {
console.log('walking');
}
}
class Person {
include Walkable;
}
Private block: Adding a private block creates a lexical scope that all methods (static or instance) have access to.
class Employees { private { var JOB_TYPES = [ 'admin', 'engineer', 'hr' ]; }
function getJobType() {
return JOB_TYPES[this.jobIdx];
}
}
Foreach:
var words = [ 'hello', 'world' ];
foreach (var word in words) {
console.log(word);
}
Shorthand functions:
// works for $1, $2 and $3
var say = #{ console.log($1) };
say("hello");
// with named arguments
var say = #(word) { console.log(word) };
say("hello");
Heredocs:
var str = <<END
this is a string
END
Interpolated Strings:
var name = "John Doe";
var message = %{Welcome #{name}};
var template = <<END:jsml
%div.hello = this.message
END
// returns html
template.result({ message: "hello" });
You can still leverage some of JS2's syntactic sugar in plain Javascript by using some of the class methods available to JS2 classes.
var NewClass = OldClass.extend({ newMethod: function () { return "hello" } });