实现说明
私有字段 in 做品牌检查可以归结为类 AccessToken。
驱动整个流程的是 for (const candidate of candidates) 这一个循环。
candidates、token 定义在模块顶层,中间不经过函数作用域。
使用要点
- 直接运行文件,输出会带上标签,比如
same brand:、plain object:——输出的每一行都能指回产生它的那次调用。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 状态都挂在模块顶层:candidates、token。
核心语句
return typeof candidate === 'object' && candidate !== null && #value in candidate;
return typeof value === 'object' && value !== null && #value in value;
return String(this.#value).length;
代码示例
// `#field in obj` tests the private slot: branding without exposing values.
class AccessToken {
#value;
constructor(value) {
this.#value = value;
}
get charLength() {
return String(this.#value).length;
}
static isAccessToken(value) {
return typeof value === 'object' && value !== null && #value in value;
}
static isSameBrand(candidate) {
// Inside the class body, `in` can check any object for the slot
return typeof candidate === 'object' && candidate !== null && #value in candidate;
}
}
const candidates = [new AccessToken('secret'), {}, { value: 'fake' }, null];
for (const candidate of candidates) {
const branded = AccessToken.isAccessToken(candidate);
console.log(branded ? `token of ${candidate.charLength} chars` : 'not a token');
}
const token = new AccessToken('opensesame');
console.log('same brand:', AccessToken.isSameBrand(token));
console.log('plain object:', AccessToken.isSameBrand({}));