[英]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.callee
和arguments.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 被虐待”的評論。 要么你能夠捕捉
window
,self
,v8::Isolate
v8::context
在fetch中擴展為 cloudflare 工作人員(或使用this
的class
),或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 loop , thisArg
參數將是{demo:fn()}
var test = {demo:{}}
const createNamedFunc = (body) => {
test.demo = return {
[name]: function () {
return body.apply(body, arguments);
} } [name];
}
createNamedFunc(function body (){})
我收集這個“功能方法參數對象”是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.