var test = {
demo: function(){
//get the caller context here
}
}
//when this gets called, the caller context should be window.
test.demo();
Run Code Online (Sandbox Code Playgroud)
我试过arguments.callee和arguments.callee.caller,并没有运气...
ota*_*tay 45
由于this关键字引用ThisBinding于a LexicalEnvironment,而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"
Run Code Online (Sandbox Code Playgroud)
顺便提一下,arguments.caller已弃用.
函数this关键字的值由调用设置,它不是“上下文”。函数具有执行上下文,包括其this值。没有定义this。
无论如何,由于所有函数都具有作为this其变量对象的属性的变量,因此this除非将其传递给函数,否则您不能在范围内引用任何其他关键字。您不能直接访问变量对象。您依赖于作用域链上的变量解析,因此this将始终是当前执行上下文的this。
| 归档时间: |
|
| 查看次数: |
25326 次 |
| 最近记录: |