javascript - How to get the name of caller function? -


let consider 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 bird types correctly set, determine type on bird level. however, achieve that, need know function called bird. however, if this:

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

then make sure foo().gettype() results in undefined. possible?

you don't need 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 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -