[英]make javascript literal inheriting from different prototype
I have a some code that probably goes against what is good practice. 我有一些代码可能与良好做法背道而驰。 However, this is not what I want comments on - this is purely academic.
但是,这不是我要评论的内容-这纯粹是学术性的。
<html>
<head>
<script>
function run() {
var fakeContext = {
Array : fr.contentWindow.Array || fr.Array; //Another context/window array
}
fakeContext.Array.prototype.remove = function(el) {/*some code*/};
with (fakeContext) {
var someCode = "var x = ['1', '2']; x.remove('2')";
eval(someCode);
}
}
</script>
</head>
<body>
<iframe src="about:blank" name="fr"></iframe>
</body>
</html>
This array created when evaluating someCode inherits from the top level Array in which the code runs instead of inheriting from the fakeContext.Array
. 评估someCode时创建的此数组从运行代码的顶级Array继承,而不是从
fakeContext.Array
继承。 Meaning the array x does not have the prototype function .remove()
表示数组x没有原型函数
.remove()
How can I (if there is a way) get the literals in the someCode
-string to inherit from the fakeContext
s Array.prototype
? 我(如果有办法)如何获取
someCode
-string中的文字以从fakeContext
的Array.prototype
继承?
The problem is that an Array literal []
does not evaluate in the same way as new Array()
. 问题是Array文字
[]
计算结果与new Array()
。 The first will just create a native Array
object, while the second checks the scope for a Array
variable and executes it as a constructor. 第一个将仅创建本机
Array
对象,而第二个将检查Array
变量的范围并将其作为构造函数执行。
var fakeWin = fr.contentWindow || fr;
var fakeContext = {Array: fakeWin.Array};
with (fakeContext) {
Array.prototype.remove = function(el) {/*some code*/};
eval("var x = new Array('1', '2'); x.remove('2')");
}
To create Arrays with a prototype from a different context, you will need to eval
the literals in the fake window environment: 要使用来自不同上下文的原型创建数组,您将需要在假窗口环境中
eval
文字:
var fakeWin = fr.contentWindow || fr;
with (fakeWin) {
Array.prototype.remove = function(el) {/*some code*/};
eval("var x = new Array('1', '2'); x.remove('2')");
}
// or:
fakeWin.Array.prototype.remove = function(el) {/*some code*/};
fakeWin.eval("var x = new Array('1', '2'); x.remove('2')");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.