-1

I wanted to call a method within a method of the same class.

function Dialog() {

this.close = function() {
    //code
};

this.dialog = document.createElement("div");
this.dialog.onclick = function() {
    this.close();
}
document.body.appendChild(this.dialog);
}

var test = new Dialog();

I searched for anwers but nothing helped: I still get TypeError: this.close is not a function in the console of my browser when I click the the div.

p98
  • 15
  • 1
  • 4

2 Answers2

1

When you use function() { ... } it changes what this is while inside the function. You either need to bind the function to this or use an arrow function () => { ... }.

Using bind:

var handleClick = function() {
    this.close();
};

this.dialog.onclick = handleClick.bind(this)

Using arrow function:

this.dialog.onclick = () => {
    this.close();
}
Brett Merrifield
  • 2,220
  • 6
  • 22
  • 21
0

Try using close(){} instead of doing this.close = function(){}. See example below.

function Dialog() {
    close(){
        //code
    };

    this.dialog = document.createElement("div");
    this.dialog.onclick = function() {
        this.close();
    }

    document.body.appendChild(this.dialog);
}

var test = new Dialog();
Paolo
  • 823
  • 6
  • 18