简体   繁体   English

覆盖JavaScript中的数组文字

[英]Overriding array literal in JavaScript

My app (a custom web browser) is injecting code into a page that has a modified Array prototype (specifically because it uses prototype.js). 我的应用程序(自定义Web浏览器)正在将代码注入具有修改后的Array原型的页面(特别是因为它使用prototype.js)。 I would like to ensure that the code I inject uses the normal Array . 我想确保注入的代码使用正常的Array I am using the code from https://stackoverflow.com/a/15147986/502149 to reset the prototype, and this works fine if I say: 我正在使用https://stackoverflow.com/a/15147986/502149中的代码重置原型,如果我说:

(function(Array) {
  var array = new Array();
)(ArrayWithUnmodifiedPrototype);

However, I still get the modified prototype if I say: 但是,如果我说:

(function(Array) {
  var array = [];
)(ArrayWithUnmodifiedPrototype);

I'm not sure if this is going to be a problem (some third-party libraries in the code I inject could theoretically use [] ) but either way I'm curious: is there any way to override [] so it uses a different prototype than that of the current Array.prototype in global scope? 我不确定这是否会成为问题(我注入的代码中的某些第三方库在理论上可以使用[] ),但是我很好奇:无论哪种方法都可以覆盖[]因此它使用了全局范围内与当前Array.prototype不同的原型?

No, there isn't. 不,没有。 This is actually one of the good things about using literals. 这实际上是使用文字的好处之一。 :-) But in your particular unusual situation, it's less helpful. :-)但是在您特殊的情况下,它的帮助会更小。

Just for completeness: 仅出于完整性考虑:

Given that you do apparently have a reference to an Array.prototype that isn't modified (I'm basing this on your ArrayWithUnmodifiedPrototype symbol), you could get around this by swapping things each time you need to create an array or call one of those third-party libraries. 鉴于您显然确实引用了未修改的Array.prototype (我将其基于ArrayWithUnmodifiedPrototype符号),因此可以在每次需要创建数组或调用其中一个时通过交换内容来解决此问题。这些第三方库。 (This is obviously less than ideal.) (这显然不理想。)

Eg: 例如:

var oldPrototype = Array.prototype;
Array.prototype = ArrayWithUnmodifiedPrototype.prototype;
/*...call third-party lib that might use []...*/
Array.prototype = oldPrototype;

But if the third-party stuff is processing things in ajax callbacks and such, you'd probably struggle to slip your code in to swap the prototypes around. 但是,如果第三方的东西正在处理ajax回调之类的事情,那么您可能会很难插入代码以交换原型。

Probably the best thing is to ensure the code you inject works with any reasonable modifications to Array.prototype (such as the ones PrototypeJS does, which are mostly reasonable despite the fact it still overwrites things like Array.prototype.map even if they're there...). 也许最好的办法是确保您注入的代码可以对Array.prototype进行任何合理的修改(例如PrototypeJS所做的修改,尽管即使它们仍然会覆盖Array.prototype.map东西,但大多数情况下这都是合理的)那里...)。

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

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