Symbol
Symbol是怎么样的一种数据结构
Symbol是js基本类型的第七种数据类型(null, undefind, number, string, boolean, object)————Symbol。
Symbol不是对象,更想是一种类字符串,但是是唯一的,所以不能往Symbol上面赋值属性;
为什么要有Symbol
Symbol的引入就是为了解决对象属性名冲突的一个问题,保证每一个属性都是唯一的;
使用Symbol注意点
-
- Symbol用于做对象属性名时,不能用点运算符;要用方括号;点运算符是指代一个具体属性,symbol的值某一种程度上还是一个变量的存在;
-
- 遍历获取Symbol健名,Object.getOwnPropertySymbols,Reflect.ownKeys;
应用场景:
1、 魔术字符串 --- 字符串是一个常量枚举值 ,作为属性值;
const shapeType = {
triangle: Symbol()
}
function getArea(shape, options) {
var area = 0;
switch (shape) {
case shapeType.triangle:
area = 0.5*options.width*options.height;
break;
}
return area;
}
getArea(shapeType.triangle, {width: 100, height: 100});
单例 --- 保证这个单例的值不会被拿到修改和覆盖;
const FOO_KEY = Symbol('foo');
function A() {
this.foo = 'hello';
}
if(!global[FOO_KEY]) {
global[FOO_KEY] = new A();
}
module.exports = global[FOO_KEY];
koa洋葱模型
概念:洋葱模型的图很具体;
API
- api: app.use() 添加中间件到应用中
- api:默认执行第一个中间件,如果要执行多个next()函数来调用;
- api: next函数返回的是一个promise;
中间件例子
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
console.log(1)
await next();
console.log(5)
const rt = ctx.response.get('X-Resoponse-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx,next) => {
const start = Date.now();
console.log(2)
await next();
console.log(4)
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
console.log(3)
ctx.body = 'hello world';
})
app.listen(3000);
// console
// GET / - 7ms
// 1
// 2
// 3
// 4
// 5
为什么要有洋葱模型
- 业务分层处理,合理的架构;
koa洋葱模型的实现 ——— 源码解析两点:
- middleware是一个队列,收集所有的一个中间件;
- 将context一路传递下去;
- 将middleware下一个中间件的fn作为未来next的返回值;