gpt4 book ai didi

javascript - 如何更改 new Function(...) 的全局上下文?

转载 作者:行者123 更新时间:2023-12-03 10:14:57 24 4
gpt4 key购买 nike

我想指定给定函数的全局上下文,同时保持其本地范围不变。经过一些research结果很接近并且有些工作:

// that iframe is created via document.write to share objects 
var iFrameGlobal = myIFrameGlobal;

(function( ns ) {
var context = this; // is the iframe's global, correct!
}( iFrameGlobal ));

现在如前所述,我想完整保留该 iframe 上下文中函数的作用域:

 var realGlobal = window;// the creator source of the iframe

var iFrameGlobal = myIFrameGlobal;


(function( ns ) {


// is the iframe's global, correct!
var context = this;

// button is a custom HTML element in the iFrame, its owner document
// is correct. Its basically a custom widget, its JS has been parsed
// in that iframe as well.
var myWidget = button;

//the content of the new function
var script = "var context = window; console.dir(context); return context";

var fn = new Function("{" + script + "}");

var result = fn.apply(myWidget, _args || {});//returns realGlobal


}( iFrameGlobal ));

正如您所看到的,更改全局上下文确实有效,但是当解析新函数时,上下文确实回退到其父文档。

这是故意的吗?我还看到了这个答案 here其中提到了这种行为,但对我来说没有意义,因为“this”是正确的,并且下面的函数应该遍历到它。

ps:

  • 已针对 Firefox-29 和 Firebug 1.12 进行了测试(必须在其中运行)
  • 实际上,我想在该 iframe 中运行包含 $('#otherButton').css(...) 的“脚本”,通过 fn.apply(myWidget,...) 传递的自定义范围内;

最佳答案

要将函数绑定(bind)到上下文,您必须使用bind(object)。

 var realGlobal = window;// the creator source of the iframe

var iFrameGlobal = myIFrameGlobal;


(function( ns ) {


// is the iframe's global, correct!
var context = this;

// button is a custom HTML element in the iFrame, its owner document
// is correct. Its basically a custom widget, its JS has been parsed
// in that iframe as well.
var myWidget = button;

//the content of the new function
var script = "var context = window; console.dir(context); return context";

var fn = new Function("{" + script + "}").bind(this);

var result = fn.apply(myWidget, _args || {});//returns realGlobal


}( iFrameGlobal ));

关于javascript - 如何更改 new Function(...) 的全局上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com