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

Hi,

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,
Karin

First case is a global context (i.e. window object): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#Global_context

Second case is the prototype chain: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_on_the_objects_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.

Greets,
Karin

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): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

1 Like