Get the calling class in JavaScript

Is it possible to get a class that calls a function in JavaScript?

For instance:

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

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

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

+3
source share
3 answers

Try the following:

function alertCaller(){
    alert(this.constructor);
}
+4
source

You really need to use strict mode

What is strict mode?

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

Perhaps the best design meets your needs.


If you still want to get the caller

This is what you would use if you did not enable strict mode.

function alertCaller(){
    alert(arguments.callee.caller);
}
+2
source

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
source

All Articles