0

I have the following code which I am confused why when I define a prototype of property 'name' it comes out as '40' and not 'fred'? what is going on inside javascript? this seems like a simple question but one that I am confused about. Thanks!

function Product(id){
    this.id = id
    this.name = id + 20
}

Product.prototype.name = 'fred';
var p = new Product(20);
console.log(p.name);
2
  • Well, you set it to 40 inside the constructor - shadowing the value that would be inherited from the prototype. Commented Mar 12, 2014 at 12:38
  • thanks both of you, this seemed such an odd question when I posed it to myself as I don't normally get into a situation when I use the same name of a property on both the prototype of a constructor and within the constructor! thanks again. Commented Mar 14, 2014 at 16:19

1 Answer 1

1

Because you did this.name = id + 20.

p.name will find the name property in the instance first, if not found, then try to find in the prototype.

function Product(id){
    this.id = id
}

Product.prototype.name = 'fred';
var p = new Product(20);
console.log(p.name); // then it will be fred
Sign up to request clarification or add additional context in comments.

1 Comment

what is happening in javascript behind the scenes? can you explain please?

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.