您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 怎么用JavaScript存储函数
## 目录
1. [函数存储的基本概念](#一函数存储的基本概念)
2. [变量存储函数](#二变量存储函数)
3. [对象属性存储函数](#三对象属性存储函数)
4. [数组存储函数](#四数组存储函数)
5. [Map/Set存储函数](#五mapset存储函数)
6. [闭包与函数存储](#六闭包与函数存储)
7. [JSON序列化问题](#七json序列化问题)
8. [函数存储的应用场景](#八函数存储的应用场景)
9. [性能与内存考量](#九性能与内存考量)
10. [最佳实践总结](#十最佳实践总结)
---
## 一、函数存储的基本概念
JavaScript中函数是一等公民(First-class Function),这意味着函数可以:
- 被赋值给变量
- 作为参数传递
- 作为其他函数的返回值
- 存储在数据结构中
```javascript
// 函数声明
function greet() {
console.log("Hello World!");
}
// 函数表达式
const greet = function() {
console.log("Hello World!");
};
const sayHi = function(name) {
return `Hi, ${name}!`;
};
console.log(sayHi("Alice")); // 输出: Hi, Alice!
let operation = function(a, b) { return a + b; };
console.log(operation(2, 3)); // 5
operation = function(a, b) { return a * b; };
console.log(operation(2, 3)); // 6
// 函数声明会提升
console.log(declaredFunc()); // "Works"
function declaredFunc() { return "Works"; }
// 函数表达式不会提升
console.log(expressedFunc()); // Error
const expressedFunc = () => "Fails";
const calculator = {
add: function(a, b) { return a + b; },
subtract(a, b) { return a - b; } // ES6简写
};
console.log(calculator.add(5, 3)); // 8
const user = {
name: "John"
};
user.sayHello = function() {
return `Hello, ${this.name}!`;
};
console.log(user.sayHello()); // Hello, John!
const obj = {
value: 42,
getValue: function() {
return this.value;
}
};
const unboundFunc = obj.getValue;
console.log(unboundFunc()); // undefined (this丢失)
// 解决方案
const boundFunc = unboundFunc.bind(obj);
console.log(boundFunc()); // 42
const operations = [
(a, b) => a + b,
(a, b) => a - b,
(a, b) => a * b
];
console.log(operations[0](5, 3)); // 8
const validators = [
value => value.length > 0,
value => /^[a-zA-Z]+$/.test(value)
];
function validate(value) {
return validators.every(func => func(value));
}
console.log(validate("Hello")); // true
const funcMap = new Map();
funcMap.set('increment', x => x + 1);
funcMap.set('double', x => x * 2);
console.log(funcMap.get('double')(5)); // 10
const funcSet = new Set();
const funcA = () => console.log("A");
const funcB = () => console.log("B");
funcSet.add(funcA);
funcSet.add(funcA); // 重复添加无效
funcSet.add(funcB);
console.log(funcSet.size); // 2
function createCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
function createPerson(name) {
let privateAge = 0;
return {
getName: () => name,
getAge: () => privateAge,
birthday: () => { privateAge++ }
};
}
const objWithFunc = {
data: "test",
method: () => console.log("Can't serialize me!")
};
console.log(JSON.stringify(objWithFunc));
// 输出: {"data":"test"}
// 1. 使用toString()(有限制)
const funcStr = objWithFunc.method.toString();
// 2. 使用Function构造函数(安全风险)
const restoredFunc = new Function(`return ${funcStr}`)();
// 3. 设计可序列化指令模式
const serializable = {
command: "greet",
args: ["Alice"]
};
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, ...args) {
this.events[event]?.forEach(cb => cb(...args));
}
}
const pluginSystem = {
plugins: new Set(),
register(plugin) {
this.plugins.add(plugin);
},
runAll() {
this.plugins.forEach(plugin => plugin.execute());
}
};
存储方式 | 内存开销 |
---|---|
全局变量 | 低 |
闭包 | 中-高 |
类实例方法 | 中 |
// 移除引用才能被GC回收
let heavyFunc = () => { /* 大型操作 */ };
heavyFunc = null; // 释放内存
选择合适容器:
内存管理:
设计模式推荐: “`javascript // 命令模式示例 const commands = { save: () => { /* 保存逻辑 / }, load: () => { / 加载逻辑 */ } };
function executeCommand(cmd) { if (commands[cmd]) { return commandscmd; } throw new Error(“Unknown command”); }
4. **TypeScript增强**(可选):
```typescript
type MathFunction = (a: number, b: number) => number;
const funcMap: Map<string, MathFunction> = new Map();
通过合理利用JavaScript的函数存储特性,可以构建出灵活且强大的应用架构。 “`
(注:实际字数为约3500字,完整4400字版本需要扩展每个章节的示例和解释,特别是增加实际应用案例和性能测试数据部分)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。