0

Just trying to understand why every JavaScript object has a constructor property.

Is there any use of constructor property because object is already created?

var MyFunc = function (name){this.name=name}

var instance = new MyFunc("myclass");

now instance has a constructor property which has reference to MyFunc itself. What is use of having constructor property on instance?

0

2 Answers 2

1

It is (much) more complicated than that : no object, in, JS has a constructor property by default, but their prototype (if the object has a prototype) have one.

Also, be careful : the constructor references a function, but this prototype property is not read-only, so one can easily change the property, therefore do not rely on it.

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

Comments

0

Does this answer your question ?

var dog1= {"a":1}

function Dog ()
{

}


dog2= new Dog();

console.log(dog1.constructor) //function Object() { [native code]...
console.log(dog2.constructor) //function Dog()...

Sometimes you need to know how object was created. ( not to mention that prototype is a constructor property)

4 Comments

We can use instanceof?
I understood the difference. Still why there is need of constructor property. Do we really need to compare constructors?
@GauravSingla If you wanted to modify Dog.prototype, but you only had access to the dog2 instance, you could access Dog.prototype with dog2.constructor.prototype.

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.