1

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.

3
  • why don't you check it by yourself? Commented Oct 4, 2013 at 20:13
  • How do you mean? What I actually want to do is customize the method so that it will behave differently depending on how it is called. Commented Oct 4, 2013 at 20:17
  • Your function declarations have syntax errors, remove the =! Then, Why use a function as the prototype? Commented Oct 4, 2013 at 20:19

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.