JavaScript 是一种动态、解释型的编程语言,主要用于网页开发,但如今已通过 Node.js 等环境扩展到服务端和桌面应用。以下是 JavaScript 的核心特性:
let x = 10; // 数字
x = "hello"; // 字符串
class
是语法糖)。function Person(name) { this.name = name; }
Person.prototype.greet = function() { console.log(`Hello, ${this.name}!`); };
const alice = new Person("Alice");
alice.greet(); // "Hello, Alice!"
const sayHi = () => console.log("Hi");
function runFunction(fn) { fn(); }
runFunction(sayHi); // "Hi"
async/await
处理异步操作:// Promise
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
// async/await
async function getData() {
const response = await fetch(url);
const data = await response.json();
console.log(data);
}
button.addEventListener("click", () => {
console.log("Button clicked!");
});
setTimeout
、AJAX)由浏览器 API 处理,完成后回调进入任务队列等待执行。function outer() {
const name = "Alice";
function inner() { console.log(name); }
return inner;
}
const innerFunc = outer();
innerFunc(); // "Alice"(访问了 outer 的变量)
import/export
模块化开发:// math.js
export const add = (a, b) => a + b;
// app.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
const [a, b] = [1, 2]; // 解构赋值
const message = `Hello ${a + b}`; // 模板字符串
eval()
或 Function
构造函数动态执行代码字符串(需谨慎使用)。JavaScript 的核心特性使其适合快速开发、灵活适应多种场景,但也需注意其动态类型、异步处理等带来的复杂性。现代 JavaScript(ES6+)通过类、模块化等语法糖进一步提升了开发体验。