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
  • 6,115
  • 16
  • 50
  • 57
Ood
  • 1,445
  • 4
  • 23
  • 43

3 Answers3

4

Try this :

function alertCaller(){
    alert(this.constructor);
}
Serge K.
  • 5,303
  • 1
  • 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,769
  • 2
  • 31
  • 50
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,351
  • 12
  • 42
  • 69
  • This is also a good method for passing variables to certain functions only! Thank you! – Ood Feb 12 '14 at 15:36