覆盖JavaScript中的数组文字 [英] Overriding array literal in JavaScript
问题描述
我的应用程序(自定义Web浏览器)将代码注入到具有修改后的 Array
原型的页面中(特别是因为它使用了prototype.js)。我想确保我注入的代码使用普通的 Array
。我正在使用 https://stackoverflow.com/a/15147986/502149 中的代码重置原型,如果我说:
My app (a custom web browser) is injecting code into a page that has a modified Array
prototype (specifically because it uses prototype.js). I would like to ensure that the code I inject uses the normal Array
. I am using the code from https://stackoverflow.com/a/15147986/502149 to reset the prototype, and this works fine if I say:
(function(Array) {
var array = new Array();
)(ArrayWithUnmodifiedPrototype);
但是,如果我说:
(function(Array) {
var array = [];
)(ArrayWithUnmodifiedPrototype);
我不确定这是否会成为问题(某些第三方库我注入的代码理论上可以使用 []
),但是我好奇的是,有两种方法可以覆盖 []
因此它在全球范围内使用与当前 Array.prototype
不同的原型吗?
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?
推荐答案
不,没有。这实际上是使用文字的好处之一。 :-)但在您特殊的情况下,它的作用会较小。
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.
仅出于完整性考虑:
给出您显然确实引用了未修改的 Array.prototype
(我基于您的 ArrayWithUnmodifiedPrototype
符号),则可以通过在每次需要创建数组或调用这些第三方库之一时交换内容来解决此问题。 (显然,这不理想。)
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. (This is obviously less than ideal.)
例如:
var oldPrototype = Array.prototype;
Array.prototype = ArrayWithUnmodifiedPrototype.prototype;
/*...call third-party lib that might use []...*/
Array.prototype = oldPrototype;
但是如果第三方的东西正在处理ajax回调之类的东西,您可能会很挣扎
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.
也许最好的办法是确保您注入的代码可以对合理进行任何修改 Array.prototype
(例如PrototypeJS所做的,尽管它仍然会覆盖 Array.prototype.map
即使他们在那里...)。
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...).
这篇关于覆盖JavaScript中的数组文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!