-1

I was looking into Javascript objects and prototypes, as far as I knew, the two ways of defining constructors ends up with similar results.

For example in this code the same exact constructors are defined in 2 different ways yet they end up with different prototype values:

var PersonOne = function () {};

function PersonTwo(){};

var p1 = new PersonOne();
var p2 = new PersonTwo();

console.log(p1.constructor.prototype);
console.log(p2.constructor.prototype);

result:

Object {}
PersonTwo {}

Obviously I was wrong about that and defining the constructor like in PersonOne results in a constructor who's prototype is Object. And that would affect inheritance. But the question is, what is the reason for such a different result?

I think the issue might be due to the fact that PersonOne function gets defined on run-time while PersonTwo on parse-time? Thanks for the help.

1 Answer 1

3

The difference is that PersonOne has been assigned the result of an anonymous function expression. The named variable is just an alias for that function, but the constructor function itself has no .name property.

If instead you had declared it:

var PersonOne = function MyPersonOne() {};

then the prototype of an object created as a new PersonOne would be MyPersonOne.

This is important - it ensures that you can't create objects of arbitrary "type" just by creating an alias to a constructor. The "type" of the object must be the same as the (real) name of the constructor function.

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

1 Comment

Excellent point, thanks for the clarification now I get it :)

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.