簡體   English   中英

是否可以在javascript中獲取調用者上下文?

[英]Is it possible to get the caller context in javascript?

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

奇怪的是我們是如何談論this的,除了
“Qix - MONICA 被虐待”的評論。 要么你能夠捕捉

  1. window
  2. 工人self
  3. v8::Isolate v8::contextfetch中擴展為 cloudflare 工作人員(或使用thisclass ),或
  4. 重命名其他函數方法的范圍- this -context 外部,所以

這種假設情況沒有用例。

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 loopthisArg參數將是{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. 傳遞它,直到下一個非對象也不是-data-type可返回類型定義或實例化不一定是聲明,但總是實現/擴展范圍接口

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM