支付寶小程序框架 SJS·esnext

2020-09-18 10:28 更新

SJS 支持部分 ES6 語法。

let & const

function test(){
  let a = 5;
  if (true) {
    let b = 6;
  }
  console.log(a); // 5
  console.log(b); // 引用錯誤:b 未定義
}

箭頭函數(shù)

const a = [1,2,3];
const double = x => x * 2; // 箭頭函數(shù)
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, // 對象屬性
  toString() { // 對象方法
    return "string";
  },
};

注意: 不支持 super 關(guān)鍵字,不能在對象方法中使用 super。

模板字符串(template string)

const h = 'hello';
const msg = `${h} alipay`;

解構(gòu)賦值(Destructuring)

// array 解構(gòu)賦值
var [a, ,b] = [1,2,3];
a === 1;
b === 3;
// 對象解構(gòu)賦值
var { op: a, lhs: { op: b }, rhs: c }
       = getASTNode();
// 對象解構(gòu)賦值簡寫
var {op, lhs, rhs} = getASTNode();
// 函數(shù)參數(shù)解構(gòu)賦值
function g({name: x}) {
  console.log(x);
}
g({name: 5});
// 解構(gòu)賦值默認值
var [a = 1] = [];
a === 1;
// 函數(shù)參數(shù):解構(gòu)賦值 + 默認值
function r({x, y, w = 10, h = 10}) {
  return x + y + w + h;
}
r({x:1, y:2}) === 23;

Default + Rest + Spread

// 函數(shù)參數(shù)默認值
function f(x, y=12) {
  // 如果不給y傳值,或者傳值為undefied,則y的值為12
  return x + y;
}
f(3) == 15;


function f(x, ...y) {
  // y 是一個數(shù)組
  return x * y.length;
}
f(3, "hello", true) == 6;
function f(x, y, z) {
  return x + y + z;
}
f(...[1,2,3]) == 6; // 數(shù)組解構(gòu)
const [a, ...b] = [1,2,3]; // 數(shù)組解構(gòu)賦值, b = [2, 3]
const {c, ...other} = {c: 1, d: 2, e: 3}; // 對象解構(gòu)賦值, other = {d: 2, e: 3}
const d = {...other}; // 對象解構(gòu)
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號