JavaScript/Symbol

来自康健生活
Kangkk​(留言 | 贡献)2022年7月21日 (四) 17:06的版本 (→取值)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

Symbol

取值

Reflect.ownKeys

Object.getOwnPropertySymbols

假设现有一个 object,内容如下:取 session 里面的值。

{
  search: ƒ (){\n    return this[target][name];\n  }
  secure: ƒ (){\n    return this[target][name];\n  }
  socket: ƒ (){\n    return this[target][name];\n  }
  stale: ƒ (){\n    return this[target][name];\n  }
  state: {userInfo: {…}}
  status: ƒ (){\n    return this[target][name];\n  }
  subdomains: ƒ (){\n    return this[target][name];\n  }
  Symbol(context-param): {}
  Symbol(cookie-store): {}
  Symbol(think-context-session): RedisSession {options: {…}, cookieOptions: {…}, redis: thinkRedis, ctx: {…}, data: {…}, …}
    cookieOptions: {name: '__medici', autoUpdateRate: 0.5, path: '/', httpOnly: true, sameSite: false, …}
    ctx: {request: {…}, response: {…}, app: Application, req: IncomingMessage, res: ServerResponse, …}
    data: {development-user: {…}}
}

取值。

const symbolList = Object.getOwnPropertySymbols(ctx) || [];
let userId = ((ctx.state || {userInfo: {}}).userInfo || {id: ''}).id || '';
if (!userId) {
  symbolList.map(_ => {
    if (String(_) === 'Symbol(think-context-session)') {
      const sessionData = ctx[_].data || {};
      userId = (sessionData[`${think.env}-user`] || {}).id || '';
    }
  });
}