this.someValue is undefined when not part of a method on an object's prototype


Please consider the following code:

function Word(word) {
  this.word = word;
Word.prototype.letters = this.word.split('');

Immediately produces --> Uncaught TypeError: this.word is undefined

However if I turn the property into a method, it works

Word.prototype.letters = function() { 
   return this.word.split('')
const beatle = new Word("beatle")
beatle.letters() // ["b", "e", "a", "t", "l", "e"]

But why? Am I doing it wrong?
Could you help?

Thanks and Greets,

First case is a global context (i.e. window object):

Second case is the prototype chain:

1 Like

Thank you, it’s simple but I didn’t see it.
Does that mean that the length value of string or array works because length is a property that belongs to the window?

I feel so much better now.


No, it’s because length is on String/Array prototype chain (something like you did with letters for Word only already built in in JS): Array: length - JavaScript | MDN

1 Like