Home > Enterprise >  Stuck with OOP Class
Stuck with OOP Class

Time:03-01

Hello I'm trying to run this code in the OOP Class framework however there's this error of "Cannot read properties of undefined (reading 'join').

Why is that?

class Window {
  constructor(tabs) {
    this.tabs = tabs;
  }
  join(otherWindow) {
    const {tabs} = this;
    tabs = tabs.concat(otherWindow.tabs)
  }
  tabOpen() {
    const {tabs} = this;
    tabs.push('new tab')
  }
  tabClose(index) {
    const {tabs} = this;
    const tabsBeforeIndex = tabs.slice(0, index)
    const tabsAfterIndex = tabs.slice(index 1)
    tabs = tabsBeforeIndex.concat(tabsAfterIndex)
  }
}

const workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp'])
const socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']);
const videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']);

const finalTabs = socialWindow.tabOpen().join(videoWindow.tabClose(2)).join(workWindow.tabClose(1).tabOpen());

console.log(finalTabs)

CodePudding user response:

Looked at it for 3 hours and finally understood why.

  1. const{tab} = this. The destructuring returns a reference back to me and thus i cannot reassign the value of tabs (which obviously should be re-assigned all the time in this case). Therefore, use this.tabs instead.
  2. THere is no "return" so essentially undefined.
  3. Even with return I tried return this.tabs and still got undefined. The reason is that I am chaining methods, so it should be "return this", since this gives me back the object which I can apply the next method to.
  • Related