3

Is it possible to get the class calling a function in JavaScript?

For example:

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

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

When calling the Foo().alertCaller() i want to output the class Foo() and when calling Bar().alertCaller() I want to outbut Bar(). Is there any way I can do this?

Kara
  • 5,996
  • 16
  • 49
  • 56
Ood
  • 891
  • 2
  • 16
  • 34

3 Answers3

4

Try this :

function alertCaller(){
    alert(this.constructor);
}
Serge K.
  • 5,143
  • 20
  • 27
2

You really should use strict mode

What is strict mode ?

I recommend you not to do what you want to do.

There is probably a better design answering to your needs.


If you still want to get the caller

This is what you'd use if you haven't strict mode enabled

function alertCaller(){
    alert(arguments.callee.caller);
}
axelduch
  • 10,436
  • 2
  • 28
  • 49
1

if i understand you ..

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();
Muath
  • 4,271
  • 11
  • 39
  • 67
  • This is also a good method for passing variables to certain functions only! Thank you! – Ood Feb 12 '14 at 15:36