是否可以在javascript中获取调用者上下文

Is it possible to get the caller context in javascript?

本文关键字:获取 调用者 上下文 javascript 是否      更新时间:2023-09-26
var test = {
    demo: function(){
      //get the caller context here
    }
}
//when this gets called, the caller context should be window.
test.demo();

我尝试了arguments.calleearguments.callee.caller,但没有运气...

由于this关键字引用LexicalEnvironment中的ThisBinding,而javascript(或ECMAScript(不允许以编程方式访问LexicalEnvironment(实际上,没有对整个Execution Context进行编程访问(,因此不可能获得调用者的上下文。

此外,当您尝试在全局上下文中test.demo()时,根本不应该有调用方,也不应该有调用方附加上下文,这只是全局代码,而不是调用上下文。

根据上下文,我假设你的意思是this?这取决于函数的调用方式,而不是从何处调用函数。

例如(使用 Webkit 控制台(:

var test = {
    demo: function() {
        console.log(this);
    }
}
test.demo();    // logs the "test" object
var test2 = test.demo;
test2();        // logs "DOMWindow"
test.demo.apply("Cheese"); // logs "String"

顺便说一下,arguments.caller已被弃用。

函数

this关键字的值由调用设置,它不是"上下文"。函数具有执行上下文,其中包括其值。它不是由this定义的。

在任何情况下,由于所有函数都有一个 this 变量,该变量是其变量对象的属性,因此不能在作用域中引用任何其他 this 关键字,除非将其传递给函数。不能直接访问变量对象;您依赖于作用域链上的变量解析,因此this将始终是当前执行上下文的this

奇怪的是

我们如何谈论this除了
"Qix - 莫妮卡受到虐待"的评论。要么你能够捕捉

  1. window
  2. 工人self
  3. v8::Isolate v8::context在 cloudflare 工作者的获取中进行了扩展(或使用classthis(,或者
  4. 重命名其他一些函数方法的范围 - this - 上下文之外,所以

这种假设的情况没有用例。

var test = {
    demo: function(){
      //get the caller context here
    }
}
test.demo();

对于闭包,出于某种原因,可以拥有一个动态命名的函数工厂,同时保持其上下文,如下所示:

function body () {}
var test = {
  demo: {
    [name]: function () {return body.apply(body, arguments);} 
       }[name];

如果没有 for 循环,thisArg参数将{demo:fn()}

var test = {demo:{}}
const createNamedFunc = (body) => {
  test.demo = return {
    [name]: function () {
      return body.apply(body, arguments);
         } } [name];
}
createNamedFunc(function body (){})

我收集这个"函数-方法-参数-对象"是

  1. 对象声明的最深层函数方法子项
  2. 全局作用域接收器[对象]
  3. 传递它,直到下一个非对象或数据类型可返回类型定义或实例化,不一定是声明,但总是实现/扩展范围接口。