如何使用或模仿globalThis?

时间:2019-02-16 17:47:42

标签: javascript

globalThis是有效的现代Javascript全局属性...但是,

ReferenceError:全局未定义

// is working when I declare here
//      var globalThis_MyBigcache=null;
// and replace globalThis.MyBigcache to globalThis_MyBigcache below

class myClass1 {
  constructor(x) {
    this.val=x
  }
  static createMany(a) {
    return a.map(x => new myClass1(x))
  }

  get y () {
    if (!globalThis.MyBigcache)
      globalThis.MyBigcache={a:11,b:22,"...":"..."} // big object
    return (globalThis.MyBigcache[this.val]===undefined)
         ? null
         : globalThis.MyBigcache[this.val]
  }
}
let b = myClass1.createMany(["a","b","c",1,2,3,"... many"])
console.log("-- item 2, myClass1:",b[1].y) // expected 22

我需要一个并非所有类实例都克隆的属性,只需一个。

0 个答案:

没有答案