我想指定给定函数的全局上下文,同时保持其本地范围不变。经过一些research之后,这种情况变得越来越接近并且有些工作:
[root@nanderson test_mod]# cat /proc/kallsyms | grep __alloc_workqueue_key
ffffffff81084a10 T __alloc_workqueue_key
ffffffff8187a090 r __ksymtab___alloc_workqueue_key
ffffffff8188bd70 r __kcrctab___alloc_workqueue_key
ffffffff81892ba0 r __kstrtab___alloc_workqueue_key
[root@nanderson test_mod]#
现在如上所述,我想保留iframe上下文中函数的范围:
// 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 ));
正如您可能看到的那样,更改全局上下文确实有效,但在解析新函数时,上下文确实会回退到其父文档。
这是故意的吗?我也看到了这个答案here提到了这种行为,但它对我来说没有意义,因为这个'这个'是正确的,下面的函数应该遍历它。
ps:
答案 0 :(得分:1)
要将函数绑定到上下文,必须使用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 ));