Home > Software design >  is not a function, when function is right above?
is not a function, when function is right above?

Time:01-08

i often have the problem that i cant reach the Functions of my js classes inside the js class. I mostly fix it with this. or a bind(this) but why does this not work? its the exact copy the way i do this in another class.

class Page {

     // constructor and props

     ShowNewJobPopup() {
        var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
        console.log(data, element);
    }

    InitializeFilterElements(filterItems) {
        filterItems["Control"].Items.push({
            Template: function (itemElement) {
                itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
                $("#btnNeuerJob").dxButton({
                    type: "default",
                    text: "Neuer Job",
                    disabled: false,
                    onClick: function () {
                        this.ShowNewJobPopup(); // how is this not a function
                        
                    }.bind(this)
                });
            }
        });
        return filterItems;
    }
}

when im in the dev console. i can write Page.ShowNewJobPopup (Page is the script this is attached to)

CodePudding user response:

The this is actually not from the class Page.

We rewrite your Page class in the below way and you can see the this is referred to the obj.

class Page {
    constructor() {}

    ShowNewJobPopup() {
        var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
        console.log(data, element);
    }

    InitializeFilterElements(filterItems) {
        const obj = {
            Template: function (itemElement) {
                itemElement.append(
                    '<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
                );
                $("#btnNeuerJob").dxButton({
                    type: "default",
                    text: "Neuer Job",
                    disabled: false,
                    onClick: function () {
                        this.ShowNewJobPopup(); 
                    }.bind(this), // this is referred to obj
                });
            },
        };

        filterItems["Control"].Items.push(obj);
        return filterItems;
    }
}

What you can do is create a variable self to store the this and use it to reference to the class Page later.

class Page {
    constructor() {}

    ShowNewJobPopup() {
        var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
        console.log(data, element);
    }

    InitializeFilterElements(filterItems) {
        const self = this; // this here is referred to the class Page

        const obj = {
            Template: function (itemElement) {
                itemElement.append(
                    '<div id="btnNeuerJob" style="width: 100%; margin-top: 4px;"></div>'
                );
                $("#btnNeuerJob").dxButton({
                    type: "default",
                    text: "Neuer Job",
                    disabled: false,
                    onClick: function () {
                        self.ShowNewJobPopup(); // self is referred to Page Class
                    },
                });
            },
        };

        filterItems["Control"].Items.push(obj);
        return filterItems;
    }
}

CodePudding user response:

You seem to have several functions with different this contexts nested within each other. It would be much simpler just to create a variable at the top of your class method rather than worrying about passing the right context to each function.

InitializeFilterElements(filterItems) {
    const thisPage = this; // SET THE VARIABLE
    filterItems["Control"].Items.push({
        Template: function (itemElement) {
            itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
            $("#btnNeuerJob").dxButton({
                type: "default",
                text: "Neuer Job",
                disabled: false,
                onClick: function () {
                    thisPage.ShowNewJobPopup();                    
                }
            });
        }
    });
    return filterItems;
}

CodePudding user response:

The value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called.

InitializeFilterElements(filterItems) {
    const self = this; // self now holds the value of this reference
    filterItems["Control"].Items.push({
        Template: function (itemElement) {
            itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
            $("#btnNeuerJob").dxButton({
                type: "default",
                text: "Neuer Job",
                disabled: false,
                onClick: function () {
                    self.ShowNewJobPopup();                    
                }
            });
        }
    });
    return filterItems;
}

CodePudding user response:

This is a classic problem of this in JavaScript. When the Template function is invoked, the reference of this changes to whatever the context of the object, in which the function is invoked.

Checkout the example for the error

A possible fix is

class Page {

 // constructor and props

 ShowNewJobPopup() {
    var popupNewJobElement = $("<div>").attr("id", "popupNewJob");
    console.log(data, element);
}

InitializeFilterElements(filterItems) {
    var that = this;
    filterItems["Control"].Items.push({
        Template: function (itemElement) {
            itemElement.append("<div id=\"btnNeuerJob\" style=\"width: 100%; margin-top: 4px;\"></div>");
            $("#btnNeuerJob").dxButton({
                type: "default",
                text: "Neuer Job",
                disabled: false,
                onClick: function () {
                    this.ShowNewJobPopup(); // how is this not a function
                    
                }.bind(that)
            });
        }
    });
    return filterItems;
}

}

class A {

  test() {
    console.log("test")
  }

  test2() {
    let a = []
    a.push({
      template() {
        function abc() {
          console.log(this)
          this.test()
        }
        abc.bind(this)()
      }
    })
    return a
  }

}

let a = new A()

let arr = a.test2()

//this will work
arr[0].template.bind(a)()
console.log("===========")
arr[0].template()

  •  Tags:  
  • Related