【问题标题】:Get the calling Class in JavaScript [duplicate]在 JavaScript 中获取调用类 [重复]
【发布时间】:2014-03-11 00:17:37
【问题描述】:

是否可以让类在 JavaScript 中调用函数?

例如:

function Foo(){
this.alertCaller = alertCaller;
}
function Bar(){
this.alertCaller = alertCaller;
}

function alertCaller(){
    alert(*calling object*);
}

当调用 Foo().alertCaller() 时,我想输出类 Foo(),当调用 Bar().alertCaller() 时,我想输出 Bar()。有什么办法可以做到吗?

【问题讨论】:

  • caller... 但在严格模式下无效。
  • 是的,我知道没有解决方法?
  • @kei 不,我在这里尝试做不同的事情。
  • JavaScript 什么时候有了类? ;)

标签: javascript


【解决方案1】:

试试这个:

function alertCaller(){
    alert(this.constructor);
}

【讨论】:

  • 这将显示当前对象类而不是调用者的
【解决方案2】:

你真的应该使用严格模式

What is strict mode ?

我建议你不要做你想做的事。

可能有更好的设计可以满足您的需求。


如果你还想得到调用者

如果您没有启用严格模式

,这就是您所使用的
function alertCaller(){
    alert(arguments.callee.caller);
}

【讨论】:

    【解决方案3】:

    如果我理解你的话..

    function Foo(){
        this.alertCaller = alertCaller;
    }
    function Bar(){
        this.alertCaller = alertCaller;
    }
    Foo.prototype.alertCaller = function() { alert('Foo'); }
    Bar.prototype.alertCaller = function() { alert('Bar'); }
    foo = new Foo();
    foo.alertCaller(); 
    Bar= new Foo();
    Bar.alertCaller();
    

    【讨论】:

    • 这也是只将变量传递给某些函数的好方法!谢谢!
    猜你喜欢
    • 2011-07-11
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2016-09-20
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多