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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.