0

I've ready quite a bit of blog post and stackoverflow questions but can't get good understanding regarding this.

Why is it necessary to set the prototype constructor?

Trying to understand the difference between prototype and constructor in JavaScript

Constructors in JavaScript objects

JavaScript inheritance and the constructor property

Understanding the difference between Object.create() and new SomeFunction()

Question:

function person(fname) {
  this.fname = fname;
}

let obj1 = new person('first'); //works well
console.log(obj1);
let obj2 = new person.prototype.constructor('second'); //works well
console.log(obj2);
//now the query
console.log(person.constructor); //1. it prints  function Function() { [native code] } what does it mean
let obj3 = new person.constructor('third') // 2. why this doesn't work ?
console.log(obj3); //

now as we know that a every function in javascript has a property call prototype which is an object which has a property called constructor which points back to the function on which prototype object is a property. - correct me if I'm wrong with this

so according to above statement person.prototype.constructor === person (both are the same)

Query: 1 person.constructor prints function Function() { [native code] } what does it means, please explain in detail.

Query: 2 why this new person.constructor('randon') doesn't work ?

Query: 3 what exactly is person.constructor and how it's different from person.prototype.constructor ?

1 Answer 1

1

Roughly:

  1. Function constructors are implemented by the JS engine, the engine you're using implements it in native code (maybe they all do).

  2. Define "works"; it creates a new function (see #1) with the string passed in as its body, which unsurprisingly blows up if you run the returned function. If you passed in a valid function body, it works fine, e.g.,

> let obj3 = new person.constructor("console.log('hi')")
> obj3()
hi
  1. #1 and #2 answer this.
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.