假设我有一个在窗口OtherWindow中创建的对象OtherObj,它与当前的窗口ThisWindow不同:

const ThisWindow = window;
const ThisObj = ThisWindow.history;

const OtherWindow = window.open();
const OtherObj = OtherWindow.history;

console.log(ThisObj instanceof Object); //true
console.log(OtherObj instanceof Object); //false
console.log(OtherObj instanceof OtherWindow.Object); //true, but this method only if I already have a reference to OtherWindow

现在想象一下,如果我only引用了OtherObj,有没有办法得到用来创建它的窗口?也许OtherObj上有一个属性包含对创建它的窗口的引用?

我目前正试图想出一种跨窗口的方法来使用instanceof操作符.如代码示例所示,如果变量指向在当前窗口外创建的对象,[variable] instanceof Object将返回false.

你们中的一些人可能会说只使用OtherObj instanceof OtherWindow.Object(返回true),但只有当我已经有了OtherWindow的引用时,这才有效.我的问题是假设我还没有提到OtherWindow.

OtherObj上是否有指向创建它的窗口的属性?

推荐答案

Short answer:

const OtherWindow = OtherObj.constructor.constructor('return window')();

Long answer:

Because most things are an object in JavaScript you can access their constructor with Object.getPrototypeOf(ObjectIn).constructor, from the objects prototype. But because of the prototype chain ObjectIn.constructor has the same effect.
And because that constructor is a function, its constructor is Function. And once we have Function we can access everything from that window with Function('return ...')().

因此,获得Function的实现可以如下所示:

const getFunction = (ObjectIn) => {
  // Get ObjectIn's constructor
  const ObjectInConstructor = ObjectIn.constructor;
  // Get Function
  return ObjectInConstructor.constructor;
};

const getObject = (ObjectIn) => {
  const Function = getFunction(ObjectIn);
  return Function('return Object')();
};

const OtherWindowObject = getObject(OtherObj);
const OtherWindow = getFunction(OtherObj)('return window')();

因为StackOverflow的HTTP标头不允许open(),所以我创建了一个fiddle来演示.

Javascript相关问答推荐

我可以在useState中调用函数并使用其数据吗

React:如何将表格收件箱正确渲染为表格主体内的组件?

为什么我的第二个OnClick Isloading值在TEK查询Mutations 查询中不起作用?

Angular material 表多个标题行映射

在JavaScript中检索一些文本

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

微软Edge Select 间隙鼠标退出问题

格式值未保存在redux持久切片中

Plotly热图:在矩形上zoom 后将zoom 区域居中

类型自定义lazy Promise. all

React 17与React 18中的不同setState行为

配置WebAssembly/Emscripten本地生成问题

在grafana情节,避免冲突的情节和传说

引用在HTMLAttributes<;HTMLDivElement>;中不可用

无法读取未定义错误的属性路径名''

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

400 bad request error posting through node-fetch

为什么这个.add.group({})在教程中运行得很好,但在我的游戏中就不行了?

触发异步函数后不能显示数据

我的NavLink活动类在REACT-ROUTER-V6中出现问题