Sorry if my title is confusing, English is not my native language.
This is my code:
function x(name){
this.name = name
}
x.prototype.score = 1;
x.prototype.arr = [1, 2, 3]
x.prototype.obj = { val1: 1}
let u1 = new x('Jason')
console.log(x.prototype.score) // 1
console.log(++u1.score) // 2
console.log(x.prototype.score) // Still
/* ** */ console.log('break for array testing')/* ** */
console.log(x.prototype.arr[0]) // 1
console.log(++u1.arr[0]) // 2
console.log(x.prototype.arr[0]) // Value changed to 2
/* ** */console.log('break for object testing')/* ** */
console.log(x.prototype.obj['val1']) // 1
console.log(++u1.obj['val1']) // 2
console.log(x.prototype.arr[0]) // Value changed to 2
I'm confused if I do the following line in the code above:
++u1.score
A new property with the name score is created in the u1 object (and the value of x.prototype.score is not affected,) and as per my guess this is what's happening under the hood:
++u1.score
u1.score = u1.score + 1
Looks for score property in the u1
for increment, don't find it, then create one and assign it to the value of u1.score + 1
! Since u1.score
doesn't exist, it looks into the u1.__proto__
property, which leads to x.prototype
, and finds the score there, and do assignment based on what the value is there which happens to be 1
.
Finally, u1.score = 1
Everything makes sense!
This has created u1.score
without affecting x.prototype.score
!
However, now if we do with Object or Array, neither of them is created on my u1 object + the value inside the prototype is affected.
Now my question is: Is the due to the fact that we cant do this:
u1.randomArr[0] = true
Or Array and Object are reference types?
If someone could explain this, that'd be greatly appreciated!
Thanks!