SJS supports part of ES6 grammar.
let & const
function test(){
let a = 5;
if (true) {
let b = 6;
}
console.log(a); // 5
console.log(b); // Reference error: b is not defined
}
Arrow function
const a = [1,2,3];
const double = x => x * 2; // Arrow function
console.log(a.map(double));
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
};
console.log(bob.printFriends());
Enhanced object literal
var handler = 1;
var obj = {
handler, // Object attribute
toString() { // Object method
return "string";
},
};
Note: The
super
keyword is not supported and cannot be used in the object method.Template string
const h = 'hello';
const msg = `${h} alipay`;
Destructuring
// Array destructuring assignment
var [a, ,b] = [1,2,3];
a === 1;
b === 3;
// Object destructuring assignment
var { op: a, lhs: { op: b }, rhs: c }
= getASTNode();
// Shorthand for object destructuring assignment
var {op, lhs, rhs} = getASTNode();
// Destructured parameters
function g({name: x}) {
console.log(x);
}
g({name: 5});
// Default values in destructuring assignment
var [a = 1] = [];
a === 1;
// Function parameters: destructured parameters + default values
function r({x, y, w = 10, h = 10}) {
return x + y + w + h;
}
r({x:1, y:2}) === 23;
Default + Rest + Spread
// Default parameters
function f(x, y=12) {
// If no value is passed to y, or if the passed value is undefined, then the value of y is 12.
return x + y;
}
f(3) == 15;
function f(x, ...y) {
// y is an array
return x * y.length;
}
f(3, "hello", true) == 6;
function f(x, y, z) {
return x + y + z;
}
f(...[ 1,2,3]) == 6; // Array destructuring
const [a, ...b] = [1,2,3]; // Array destructuring assignment, b = [2, 3]
const {c, ...other} = {c: 1, d: 2, e: 3}; // Object destructuring assignment, other = {d: 2, e: 3}
const d = {...other}; // Object destructuring