1

In the following code I do not understand why the last console.log does not return 'kj18', although the pro-type has been changed before that line.

Could you please provide me an explanation?

var studentId = 'ab73';

function Student() {
  this.studentId = 'b0e1';
}

console.clear()

console.log(new Student().studentId);

Student.prototype.studentId = 'kj18'
Student.prototype.classId = '5e'

console.log(new Student().classId)
console.log(new Student().studentId) // why is not kj18
empiric
  • 7,825
  • 7
  • 37
  • 48
Radex
  • 7,815
  • 23
  • 54
  • 86
  • 2
    First, the property will looked inside the `new Student()`'s own properties. If not found, it will be looked inside `Student.prototype`. If not found there, then it will looked inside `Object.prototype`. Since, the `new Student()` object already has the `studentId` property added when you call the constructor function, it will no traverse the prototype chain. There is no `classId` property on `new Student()` object, so it will be checked on `Student.prototype`. If you use `new Student().toString()`, it will use the `Object.prototype.toString`, because Student.prototype doesn't have `toString` – adiga Jun 30 '21 at 14:22

2 Answers2

1

Because the assignment in the function Student() gets executed when you create a new instance from Student and it all happens after this assignment: Student.prototype.studentId = 'kj18'

Andor Polgar
  • 483
  • 3
  • 13
  • do you mean the `Student.prototype.studentId` get ovveridden by the value set in `function Student()`??? – Radex Jun 30 '21 at 14:07
  • Yes, normally `this.foo = 'bar'` would only affect the instance, but because `studentId` exists on the prototype, it is going to change it on the prototype. – Andor Polgar Jun 30 '21 at 14:09
  • The *temporal* order is somewhat irrelevant. The property on the instance (`this.studentId`) shadows the property of the same name on the prototype. There's both `new Student().studentId`, and `new Student().__proto__.studentId`, and the former takes precedence. – deceze Jun 30 '21 at 14:14
0

Adding a log to the "constructor" helps explain it.

var studentId = 'ab73';

function Student() {
  this.studentId = 'b0e1';
  console.log('assigned b0e1')
}

console.log(new Student().studentId);

Student.prototype.studentId = 'kj18'
console.log('assigned kj18')
Student.prototype.classId = '5e'

console.log(new Student().classId)
console.log(new Student().studentId) // why is not kj18
danh
  • 62,181
  • 10
  • 95
  • 136