简体   繁体   English

从javascript中的原型函数访问构造函数名称

[英]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? 这样,例如当我调用B.myname()时,函数主体中将使用名称“ B”吗?

Trying this.constructor.name as expected just returns 'A' every time. 按预期方式尝试this.constructor.name每次只会返回“ A”。

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/ http://jsfiddle.net/BFxnb/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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