Home > Software engineering >  Calling the this.method() inside function of another method
Calling the this.method() inside function of another method

Time:05-18

is there a way calling the createElement() method inside checkbox.off().on('click', function () {}) of checkBoxes() method? I cannot access the method inside the function within the method.

class Lists {
  constructor() {
    this.currentList = [];
    this.completedList = [];
  }


  createElement(
    value1 = undefined,
    value2 = undefined,
    value3 = undefined,
    checkboxCheck = ''
  ) {
    value3.append(`<li >
    <input type="checkbox" ${checkboxCheck}/>
      <span  >
        ${value1}
      </span>
      <div >
          <i ></i>
          <i ></i>
      </div>
      <br />
      <span >${value2}</span>
      </li>`);
  }

  checkBoxes() {
    const checkbox = $('input[type=checkbox]');

    checkbox.off().on('click', function () {
      this.createElement(value1, value2...)
    });
  }
}

CodePudding user response:

There are 3 ways.

// set 'this' to 'self' outside the function
const self = this;
checkbox.off().on('click', function () {
  self.createElement(value1, value2...)
});

//use Function.prototype.bind to pass 'this'
checkbox.off().on('click', function () {
  this.createElement(value1, value2...)
}.bind(this));

//use arrow function
checkbox.off().on('click', () => {
  this.createElement(value1, value2...)
});

but i suggest you to figure out why 'this' won't work in your codes by searching.

  • Related