简体   繁体   中英

accessing constructor name from prototype function in javascript

Is it possible to do the following:

function A() {}
function B() {}
B.prototype = A;
function C() {}
C.prototype = A;

A.prototype.myname = function() { /* get 'B' or 'C' here */ }

so that when I for example call B.myname() I will have the name 'B' available in the function body?

Trying this.constructor.name as expected just returns 'A' every time.

I suppose you're looking for this?

function A() {}
A.prototype.myname = function() {
    return this.constructor.name;   
};
function B() {}
B.prototype = new A();
B.prototype.constructor = B;
var b = new B();
console.log(b.myname()); // logs B

http://jsfiddle.net/BFxnb/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM