你可以添加一个函数来被劫持的JavaScript数组? [英] Can you add a function to a hijacked JavaScript Array?

查看:169
本文介绍了你可以添加一个函数来被劫持的JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是什么是宣布在Javascript数组时要遵循的最佳实践有关系吗?

假设一个客户端,我们姑且称之为DB库珀,有下列code必须在任何其他JavaScript code之前运行第一个要求:

Let's say a client, let's call them "D. B. Cooper", has a first requirement that the following code must run before any other JavaScript code:

Array = function(){
    alert('Mwahahahaha');
};

此外,库珀要求自定义函数必须添加到内置的阵列对象(而不是被劫持的一个)。例如,如果阵列被unhijacked,这将被用做:

Furthermore, Cooper requires that custom functions must be added to the built in Array object (not the hijacked one). For example, if Array was unhijacked, this would be done with:

Array.prototype.coolCustomFunction = function(){
    alert('I have ' + this.length + ' elements!  Cool!');
};

这将负担:

var myArray = [];
myArray.coolCustomFunction();

然而,这是不与第一要求兼容。因此,如何才能最好的满足两个D·B·库柏的要求是什么?

However, this is not compatible with the first requirement. Thus, how can you best fulfill both of D. B. Cooper's requirements?

注意: D.B.甚至写了 测试小提琴 ,以帮助确保解决方案能够满足他的要求.. 。什么家伙!

Note: D.B. even wrote a test fiddle to help make sure solutions meet his requirements...what a guy!

更新:
对于那些你们谁喜欢挑战:请尽量找到一个unhijackable跨浏览器解决了这个问题。例如,这里更劫持测试用例劫持数组,对象(此重新格式化感谢BERGI) ,Array.prototype.constructor和Object.prototype.constructor。迄今为止,它看起来像有可能是一个特定的浏览器解决了这个(见他的回答 BERGI的评论,让我们知道,如果你找到一个方法来劫持它FF),但在这一点上目前还不清楚是否有一个跨浏览器解决了这个。

Update: For those of you who like a challenge: please try to find an unhijackable cross-browser solution to this problem. For example, here's an even more hijacked test case (thanks for reformatting this Bergi) that hijacks Array, Object, Array.prototype.constructor, and Object.prototype.constructor. Thus far, it looks like there may be a browser-specific solution to this (see Bergi's comment on his answer, and let us know if you find a way to hijack it in FF), but it is unclear at this point if there is a cross-browser solution to this.

推荐答案

无论你的阵列函数/构造函数,数组字面语法总是会产生真正的数组与他们的[[原型]]设置为本地数组原型对象(一次,这是一个安全漏洞)。所以,你可以随时访问,通过使用

Whatever your Array function/constructor is, the literal syntax for arrays will always generate "real" arrays with their [[prototype]] set to the native array prototype object (once, this was a security vulnerability). So, you can always access that by using

Object.getPrototypeOf([])

即使阵列 []。构造被劫持。 (当然不是当对象被劫持,那么它获得工作的非常复杂)

even if Array or [].constructor are hijacked. (Will of course not work when Object is hijacked, then it get's really complicated)

带来D.B.下来!

如果你想使用一种变通方法,在FF 以下行将总是工作(而不是hijackable):

If you want to use a workaround, in FF the following line will always work (and is not hijackable):

[].__proto__.coolCustomFunction = coolCustomFunction;

这篇关于你可以添加一个函数来被劫持的JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆