JavaScript - 获取调用对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5238670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:18:56  来源:igfitidea点击:

JavaScript - Get calling object

javascript

提问by Van Coding

Possible Duplicate:
Javascript how do you find the caller function?

可能的重复:
Javascript 如何找到调用函数?

Hi guys!

嗨,大家好!

Is there a way to get the value of thisfrom the function which has called the current function? Look at this:

有没有办法this从调用当前函数的函数中获取 的值?看这个:

function TraceMySelf(){
    console.log(this);
}
function A(){
    TraceMySelf();
    console.log(this);
}

var a = new A();

When this code is executed, the console displays first the windowobject and then the aobject. How can I make the code display the aobject twice, with only changing line 2? I know that I could apply the function inside Awith this, but that isn't what I want.

执行此代码时,控制台首先显示window对象,然后显示a对象。如何让代码显示a对象两次,只更改第 2 行?我知道我可以在里面应用Awith函数this,但这不是我想要的。

Is this possible?

这可能吗?

Thanks for your help!

谢谢你的帮助!

回答by JoshRivers

I think this is the answer to your question: StackOverflow 280389

我认为这是您问题的答案:StackOverflow 280389

However, I think the right answer is "don't do that". I think it runs counter to how JavaScript is designed.

但是,我认为正确的答案是“不要那样做”。我认为这与 JavaScript 的设计方式背道而驰。

It might also be worth looking at jQuery Proxyfor another way of linking function and object.

也可能值得查看jQuery Proxy以获取链接函数和对象的另一种方式。