简体   繁体   English

如何限制对javascript对象的访问?

[英]How to limit access to a javascript object?

I was watching a video on making a good javascript application infrastructure. 我正在观看有关制作良好的javascript应用程序基础架构的视频。 Basically what it said was: 基本上它说的是:

  • Your application consists of components 您的应用程序包含组件
  • Components are parts of the page that can act on their own. 组件是页面的一部分,可以自行执行。
  • components can be registered into te application. 组件可以注册到te应用程序中。
  • upon registration, they get their own sandbox. 注册后,他们会得到自己的沙箱。
  • A sandbox is an component's interface to the application core. 沙箱是组件与应用程序核心的接口。
  • The core is built on top of a javascript library. 核心构建在javascript库之上。
  • Components only have access to their sandbox, not to other components, nore the core or the underlying library. 组件只能访问其沙箱,而不能访问其他组件,无论是核心还是底层库。

Now, what I'd like to make is an application where you can easily make new components. 现在,我想要的是一个可以轻松制作新组件的应用程序。 Components have their own part on tha page, their own div in which they can work. 组件在页面上有自己的部分,它们自己的div可以在其中工作。 And here comes the first part of my question: I want to give these components a copy of the jQuery object, but that has an internal restriction applied so that it can only work inside a certain containing element. 这里是我的问题的第一部分:我想给这些组件一个jQuery对象的副本,但是它有一个内部限制,因此它只能在某个包含元素内部工作。

The second part is,that even if a component has limited access to the DOM using jquery, it can still access the document. 第二部分是,即使组件使用jquery对DOM的访问权限有限,它仍然可以访问该文档。 I have tried both setting Window and Document to null, before running my test script, but the browser doesn't allow this. 在运行我的测试脚本之前,我已经尝试将Window和Document设置为null,但浏览器不允许这样做。 Is there any way that I can truly restrict the possibilities of an object to the methods of 1 object that I pass to it? 有没有什么方法可以真正地将对象的可能性限制为我传递给它的1个对象的方法?

You're mis-understanding the point here. 你在这里误解了这一点。 The intention isn't "make it 100% imposible for a component to acces anything it shouldn't". 意图不是“使组件100%不可能访问它不应该访问的任何东西”。 The ONLY way to do that is the insanely complicated step that Facebook took which is to parse the JS/HTML code and re-write it to dis-allow certain references, etc. I'm betting it took their dev team 1,000+ hours to do and there are still holes in it. 这样做的唯一方法是Facebook采取的非常复杂的步骤,即解析JS / HTML代码并重新编写它以禁止某些引用等等。我认为他们的开发团队需要花费1,000多个小时才能完成它还有洞。

Basically the intention is to give each component a sandbox to play with and then say "please only use this". 基本上,目的是为每个组件提供一个沙盒来玩,然后说“请只使用它”。 The authors then comply with the request. 然后作者遵守该请求。

Your sole other option is iFrames, in which case a component can do whatever it wants and it won't effect anything (assuming you're on a different sub-domain and you provide a parent-window proxy). 你唯一的另一个选择是iFrames,在这种情况下,一个组件可以做任何你想做的事情,它不会影响任何东西(假设你在一个不同的子域,你提供一个父窗口代理)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM