2

I am trying to push copied text into an empty array initialized by the constructor, but when the method is called, the error Cannot read property 'push' of undefined is shown. I am new to OOP and really want to start structuring my code as objects, but I always hit a snag and give up.

I have tried to modify the structure of my class by declaring the public field before the constructor and logging data to the console

When I log copyText() method to the console, I want to see the data inserted to create methods to modify/access it.

class CopyRecord {
  //    storedText;
  constructor() {
    this.storedText = [];
  }
  copyText() {
    document.addEventListener('copy', function() {
      let selectedText = window.getSelection().toString();
      console.log(selectedText);
      this.storedText.push(selectedText);
      return selectedText;
    })
  }
}
let copy = new CopyRecord();
console.log(copy.copyText());
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I made you a snippet. – mplungjan Jul 16 '19 at 12:46
  • Use an arrow function here `document.addEventListener('copy', () => {` – adiga Jul 16 '19 at 12:46
  • Adding event listeners is usually done at the start, as part of the setup process. It's true that using an arrow function will "fix" this, but judging by the last line of code, OP wants to actually *copy* the text, not setup some document listener that will copy text in the case of some future event. Removing the listener and directly executing the code will also solve the `this` problem. See here: https://jsfiddle.net/khrismuc/sgm6bey4/ –  Jul 16 '19 at 12:49
  • Thanks guys this helps out alot. I was using function(){} and the this keyword only can access the scope of that method. Huge help thanks again. –  Jul 16 '19 at 13:20

0 Answers0