0

Why does obj.constuctor.name give 2 different results if prototype is missing? How do i get the constructor name instead of "Object" if it has prototype then?

// Class with prototype
function Foo(a) {
    this.a = a;
}
Foo.prototype = {
    bar: function () {
        console.log(this.a);
    }
};
f=new Foo(1)
f.constructor.name
"Object"

// Class with no prototype
function Fooee(a) {
    this.a = a;
}

f1=new Fooee(1)
f1.constructor.name
"Fooee"
0

2 Answers 2

2

You're changing the constructor of Foo() by redefining its prototype to object {}.

You should've instead done this:

Foo.prototype.bar = function () {
   console.log(this.a);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Functions’ prototype properties have initial values that include constructor. You can try it:

function Foo() {
}

assert(Foo.prototype.constructor === Foo);

When you overwrite the entire prototype with an object, you’re clobbering that property. ({}.constructor === Object.) Just assign new properties to it instead:

Foo.prototype.bar = function () {
    console.log(this.a);
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.