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?

4
  • caller... but its invalid in strict mode. Commented Feb 12, 2014 at 15:19
  • Yeah, I know about that is there no workaround? Commented Feb 12, 2014 at 15:20
  • @kei No, I'm trying to do a different thing here. Commented Feb 12, 2014 at 15:20
  • Since when does JavaScript have classes? ;) Commented Feb 12, 2014 at 15:22

3 Answers 3

4

Try this :

function alertCaller(){
    alert(this.constructor);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That will show the current objects class not the caller's
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);
}

Comments

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();

1 Comment

This is also a good method for passing variables to certain functions only! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.