Lajos Arpad Lajos Arpad - 27 days ago 8
Javascript Question

How to get the name of caller function?

Let us consider this code example:

function Bird() {
var self = this;
this.getType = function() {
return self.type;
};
}
function Eagle() {
Bird.call(this);
this.type = "Eagle";
}
function Sparrow() {
Bird.call(this);
this.type = "Sparrow";
}
function Bat() {
Bird.call(this);
this.type = "Bat";
}

var e = new Eagle();
console.log(e.getType());


Here the
Bird
types are correctly set, but I would like to determine the type on
Bird
level. However, to achieve that, I would need to know which function called Bird. However, if I do something like this:

function foo() {
return new Bird();
}


then I would like to make sure that
foo().getType()
results in
undefined
. Is this possible?

Answer

You don't need to use call:

function Bird(self) {
  var type;
  if (self) {
    type = self.constructor.name;
  } else {
    self = this;
  }
  self.getType = function () {return type;};
}
function Eagle() {
   Bird(this);
}
var e = new Eagle();
console.log(e.getType()); // Eagle
console.log(new Bird().getType()); // undefined