跳到主要内容

ES2015+ 语法支持

JSVM2 支持部分 ES2015 (ES6) 及更高版本的现代 JavaScript 语法特性。

支持的 ES2015+ 特性

✅ 变量声明

let 和 const

// let - 块级作用域,可重新赋值
let count = 0;
count = 1; // 允许

if (true) {
let blockScoped = "只在块内可见";
console.log(blockScoped);
}
// console.log(blockScoped); // ReferenceError

// const - 块级作用域,不可重新赋值
const PI = 3.14159;
// PI = 3.14; // TypeError

const obj = { name: "张三" };
obj.name = "李四"; // 允许,只是对象内容改变

暂时性死区

console.log(x); // ReferenceError: 在声明前不能访问
let x = 5;

function example() {
// console.log(y); // ReferenceError
const y = 10;
return y;
}

✅ 箭头函数

基本语法

// 传统函数表达式
const add = function(a, b) {
return a + b;
};

// 箭头函数 - 简洁语法
const add = (a, b) => a + b;

// 单参数可省略括号
const double = x => x * 2;

// 无参数需要括号
const getRandom = () => Math.random();

// 多行函数体需要大括号和 return
const complex = (x, y) => {
const sum = x + y;
return sum * 2;
};

this 绑定特性

const obj = {
name: "对象",

// 传统方法 - this 指向调用对象
regularMethod: function() {
return this.name;
},

// 箭头函数 - this 继承外层作用域
arrowMethod: () => {
return this.name; // this 不是 obj
},

// 在方法中使用箭头函数
createHandler: function() {
return () => {
return this.name; // this 指向 obj
};
}
};

✅ 解构赋值

数组解构

const arr = [1, 2, 3, 4, 5];

// 基本解构
const [first, second] = arr;
console.log(first, second); // 1, 2

// 跳过元素
const [, , third] = arr;
console.log(third); // 3

// 剩余元素
const [head, ...tail] = arr;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]

// 默认值
const [a, b, c, d, e, f = 0] = arr;
console.log(f); // 0

// 嵌套解构
const nested = [[1, 2], [3, 4]];
const [[a1, a2], [b1, b2]] = nested;

对象解构

const person = {
name: "张三",
age: 30,
city: "北京",
country: "中国"
};

// 基本解构
const { name, age } = person;
console.log(name, age); // "张三", 30

// 重命名变量
const { name: fullName, age: years } = person;
console.log(fullName, years); // "张三", 30

// 默认值
const { name, phone = "未知" } = person;
console.log(phone); // "未知"

// 剩余属性
const { name, ...rest } = person;
console.log(rest); // { age: 30, city: "北京", country: "中国" }

// 嵌套解构
const user = {
info: {
name: "李四",
contact: {
email: "lisi@example.com"
}
}
};

const { info: { name, contact: { email } } } = user;
console.log(name, email); // "李四", "lisi@example.com"

函数参数解构

// 对象参数解构
function greet({ name, age = 0 }) {
return `Hello, ${name}! You are ${age} years old.`;
}

greet({ name: "张三", age: 25 });

// 数组参数解构
function sum([a, b, c = 0]) {
return a + b + c;
}

sum([1, 2, 3]); // 6
sum([1, 2]); // 3

✅ 扩展运算符 (Spread)

数组扩展

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// 数组合并
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

// 数组复制
const copy = [...arr1];

// 函数调用
function add(a, b, c) {
return a + b + c;
}

console.log(add(...arr1)); // 6

// 转换类似数组对象
const nodeList = document.querySelectorAll('div');
const array = [...nodeList];

对象扩展

const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };

// 对象合并
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }

// 对象复制
const copy = { ...obj1 };

// 属性覆盖
const updated = { ...obj1, b: 20 };
console.log(updated); // { a: 1, b: 20 }

✅ for-of 循环

const arr = [1, 2, 3, 4, 5];

// 遍历数组值
for (const value of arr) {
console.log(value);
}

// 遍历字符串
for (const char of "Hello") {
console.log(char); // H, e, l, l, o
}

// 与数组方法结合
for (const [index, value] of arr.entries()) {
console.log(index, value);
}

✅ 默认参数

// 基本默认参数
function greet(name = "世界") {
return `Hello, ${name}!`;
}

console.log(greet()); // "Hello, 世界!"
console.log(greet("张三")); // "Hello, 张三!"

// 默认参数可以是表达式
function createId(prefix = "user", suffix = Date.now()) {
return `${prefix}_${suffix}`;
}

// 默认参数可以引用前面的参数
function multiply(a, b = a) {
return a * b;
}

console.log(multiply(5)); // 25
console.log(multiply(5, 3)); // 15

✅ 剩余参数

// 收集所有参数
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

// 与普通参数结合
function introduce(name, age, ...hobbies) {
console.log(`我是${name}${age}`);
console.log('爱好:', hobbies.join(', '));
}

introduce("张三", 25, "读书", "游泳", "编程");

✅ 对象字面量增强

属性简写

const name = "张三";
const age = 30;

// ES5 写法
const person1 = {
name: name,
age: age
};

// ES2015 简写
const person2 = { name, age };

方法简写

const obj = {
// ES5 写法
method1: function() {
return "Hello";
},

// ES2015 简写
method2() {
return "World";
}
};

计算属性名

const prefix = "user";
const id = 123;

const obj = {
[prefix + "_" + id]: "张三",
["get" + "Name"]() {
return this[prefix + "_" + id];
}
};

console.log(obj.user_123); // "张三"
console.log(obj.getName()); // "张三"

✅ MetaProperty

new.target

function Person(name) {
if (!new.target) {
throw new Error('必须使用 new 调用');
}
this.name = name;
}

// 正确使用
const person = new Person("张三");

// 错误使用
// Person("李四"); // 抛出错误

部分支持的特性

⚠️ 模板字符串

目前 JSVM2 对模板字符串的支持有限。

⚠️ 类语法

ES2015 的 class 语法尚未完全支持。

⚠️ 模块系统

import/export 语法尚未支持。

使用示例

结合多个 ES2015+ 特性的综合示例:

// 使用现代 JavaScript 特性的用户管理系统
const createUserManager = () => {
const users = [];

return {
// 添加用户 - 使用默认参数和解构
addUser({ name, age = 0, ...otherInfo }) {
const user = {
id: users.length + 1,
name,
age,
...otherInfo,
createdAt: Date.now()
};
users.push(user);
return user;
},

// 查找用户 - 使用箭头函数和数组方法
findUsers: (predicate) => users.filter(predicate),

// 获取用户信息 - 使用 for-of 和模板字符串
getUsersInfo() {
const info = [];
for (const user of users) {
info.push(`${user.name} (${user.age}岁)`);
}
return info;
},

// 更新用户 - 使用扩展运算符
updateUser(id, updates) {
const index = users.findIndex(u => u.id === id);
if (index !== -1) {
users[index] = { ...users[index], ...updates };
return users[index];
}
return null;
}
};
};

// 使用示例
const manager = createUserManager();

manager.addUser({
name: "张三",
age: 25,
email: "zhangsan@example.com",
city: "北京"
});

manager.addUser({
name: "李四",
email: "lisi@example.com" // age 使用默认值 0
});

const adults = manager.findUsers(user => user.age >= 18);
console.log(adults);

这些现代 JavaScript 特性让代码更加简洁、可读,提高了开发效率。