Reputation: 191
Function B extends A, How to get B function name in parent function A, when I call parentMethod()
on object of B child function object.
function A() {
this.parentMethod = function() {
//alert('display B function name');
}
}
function B() {
}
B.prototype = new A();
var b = new B();
b.parentMethod();
Upvotes: 2
Views: 1078
Reputation:
Simplest Way to do this is:
function A() {
this.parentMethod = function() {
alert(this.constructor.name);
}
}
function B() {
}
B.prototype = new A();
B.prototype.constructor = B; //Add this line.
var b = new B();
b.parentMethod();
Now when you call parentMethod it will display B as a constructor name.
Upvotes: 2
Reputation: 816334
If you fix the constructor
property to point to the correct function (i.e. B
)
B.prototype.constructor = B;
Then you can access the name of the constructor function via
this.parentMethod = function() {
alert(this.constructor.name);
}
Note though that Function.name
is a non-standard property and might not work in all browsers. The alternative would be to hardcode the function name by overriding parentMethod
or adding a property to the instance with the function name. You could also just use the function reference (this.constructor
) directly, depending on what you are trying to achieve.
A better way to setup inheritance is to use Object.create
[MDN] and call the parent constructor function in the child constructor function:
function A() {}
A.prototype.parentMethod = function() {};
function B() {
A.call(this); // call parent constructor
}
B.prototype = Object.create(A.prototype); // establish inheritance
B.prototype.constructor = B;
Upvotes: 0