0

While going through the concepts of prototype. I saw below example from stackoverflow - Add new element to an existing object

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}

myObj.prototype.objProp = true;
var newObj = new myObj();

My question is what is the use of "myObj.prototype.objProp = true;" from above code snippet.

I am an beginner. Already referred other post similar to this. But couldn't make out.

Any help on this will be appreciated. Thanks.

1
  • 1
    What do you understand about the prototype? There's nothing particularly special about this specific use; re-explaining everything about the prototype won't be particularly productive, that's already been done to death. Commented Jan 28, 2016 at 11:41

1 Answer 1

0

Prototype is used for having common values in similar objects. you property objProp is available for all objects but does not belong to anyone.

When you do myObj.objProp, objProp is searched inside myObj. If not found, property is searched in __proto__.

Also note that if you define a property of same name inside object, like myObj.objProp, it will add a property in that object and not override proto one

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}

myObj.prototype.objProp = true;
var newObj = new myObj();

console.log(newObj);

console.log(newObj.objProp);

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.