mientje
September 27, 2020, 6:12pm
#1
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
jenovs
September 27, 2020, 6:22pm
#2
1 Like
mientje
September 27, 2020, 6:27pm
#3
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
jenovs
September 27, 2020, 6:42pm
#4
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