js
函数声明 / 函数表达式 / 箭头函数
1. 函数声明
使用 function 关键字定义,后面紧跟函数名。
function add(a, b) {
return a + b;
}
特点:
- 有函数提升(hoisting),可以在声明之前调用。
- 拥有自己的
name属性。 - 可以作为构造函数使用
new。
sayHi(); // 正常输出
function sayHi() {
console.log("Hi");
}
2. 函数表达式
把匿名函数或具名函数赋值给变量。
const add = function (a, b) {
return a + b;
};
特点:
- 没有提升,必须先定义后调用。
- 常用作回调函数或按条件定义函数。
3. 箭头函数
ES6 提供的新语法,更加简洁。
const add = (a, b) => a + b;
特点:
- 没有自己的
this,继承外层作用域的this。 - 没有
arguments对象,可用剩余参数代替。 - 不能作为构造函数,没有
prototype。 - 不能使用
yield,因此不能作为生成器函数。
const obj = {
data: [1, 2, 3],
getSum() {
return this.data.reduce((sum, n) => sum + n, 0);
},
};
4. 三者对比
| 特性 | 函数声明 | 函数表达式 | 箭头函数 |
|---|---|---|---|
| 提升 | ✅ | ❌ | ❌ |
| this | 动态绑定 | 动态绑定 | 词法绑定(继承外层) |
| arguments | ✅ | ✅ | ❌ |
| new 构造 | ✅ | ✅ | ❌ |
| prototype | ✅ | ✅ | ❌ |
| 适用场景 | 通用函数 | 回调 / 按条件定义 | 简洁回调 / 固定 this |
作用域链 与 闭包原理及常见应用
1. 作用域与作用域链
- 作用域是变量和函数的可访问范围,分为全局作用域、函数作用域和块级作用域(
let/const)。 - 函数内部可以访问外部变量,查找变量时从内向外逐级查找,这一层层作用域形成的链路就是作用域链。
const global = "global";
function outer() {
const outerVar = "outer";
function inner() {
const innerVar = "inner";
console.log(innerVar, outerVar, global); // inner outer global
}
inner();
}
outer();
2. 闭包
定义:闭包是函数与其词法作用域的组合。内部函数引用了外部函数中的变量,且将内部函数返回或传递出去,就形成了闭包。
原理:当外部函数执行完毕后,其变量本应被回收。但因为内部函数的作用域链中仍持有对外部函数活动对象的引用,所以外部变量依然存在,可以继续被内部函数访问。
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
3. 常见应用
① 私有变量 / 模块模式
const module = (function () {
let privateName = "secret";
return {
getName() {
return privateName;
},
};
})();
console.log(module.getName()); // secret
② 防抖 / 节流
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
③ 柯里化
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...next) => curried(...args, ...next);
};
}
④ 循环中保存变量
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0 1 2
}
4. 注意事项
- 闭包会阻止变量被垃圾回收,大量使用可能导致内存泄漏,之后应主动释放引用。
- 不要在循环中创建不必要的闭包,避免变量共享问题(通常用
let解决)。
this 指向与 call、apply、bind
1. this 的绑定规则
① 默认绑定
独立调用函数时,非严格模式 this 指向全局对象(浏览器 window),严格模式为 undefined。
② 隐式绑定
作为对象的方法调用时,this 指向该对象。
const obj = {
name: "MyObj",
getName() {
return this.name;
},
};
console.log(obj.getName()); // MyObj
③ 显式绑定
通过 call / apply / bind 指定 this。
④ new 绑定
构造函数中的 this 指向新创建的对象。
function Person(name) {
this.name = name;
}
const p = new Person("Tom");
console.log(p.name); // Tom
⑤ 箭头函数
箭头函数没有自己的 this,它的 this 由外层作用域决定,且无法通过 call / apply / bind 改变。
const fn = () => {
console.log(this);
};
fn(); // 外层 this(如 window)
2. call / apply / bind 用法
三者都可以显式指定 this,区别如下:
| 方法 | 执行时机 | 参数形式 | 返回值 |
|---|---|---|---|
call | 立即执行 | 参数列表 | 函数结果 |
apply | 立即执行 | 参数数组 | 函数结果 |
bind | 不立即执行 | 参数列表 | 新函数 |
function showInfo(age, city) {
console.log(`${this.name}, ${age}, ${city}`);
}
const user = { name: "Alice" };
showInfo.call(user, 25, "Beijing");
showInfo.apply(user, [25, "Shanghai"]);
const boundShow = showInfo.bind(user, 26);
boundShow("Guangzhou");
3. 常见的 this 丢失场景及解决
将对象方法赋值给变量后调用,
this丢失。const getName = obj.getName; getName(); // this 为 window / undefined解决:
const getName = obj.getName.bind(obj)或使用箭头函数。回调函数中,使用箭头函数保持外层
this。bind生成的函数,this被永久绑定,不能再被call/apply修改。
4. 总结
this 是调用时确定的,箭头函数是定义时确定的。理解作用域链和闭包是理解 this 的基础,掌握 call / apply / bind 可以在需要时精确控制 this。
c++
WebService
打包MySQL队列
// 方式1:最简单的 lambda
Sql::MySQLTask task1 = [](Sql::Connection* conn) {
MYSQL_RES* res = conn->QueryReturn("SELECT * FROM user");
// ... 处理查询结果 ...
};
// 方式2:需要外部数据时,用捕获列表带进来
int userId = 1001;
Sql::MySQLTask task2 = [userId](Sql::Connection* conn) {
conn->QueryNoReturn("UPDATE user SET status=1 WHERE id=" + std::to_string(userId));
};
// 方式3:也可以传一个已有的函数
void MySqlBusiness(Sql::Connection* conn) {
conn->QueryNoReturn("INSERT INTO log ...");
}
Sql::MySQLTask task3 = MySqlBusiness;
