Why does "this" in function statement point to a wrong scope between components?

299 Views Asked by At
  • I have a component which is used several times on one page.
  • The first line of code in the controller stores "this" in "self" in order to always refer to the right scope.
  • When I call a function statement, and I refer to self.content (which is filled with a unique array for all components), self, always refers to the last created component instead of itself.

Why does self.content suddenly refer to a different scope with a function statement (function validateContent() instead of self.validateContent = function () {...}?

I've cirucmvented this problem by making the function statement an inline one on self self.validateContent = function() {...}.

component('panel', {
    binding: {
    Content: '<'    // is filled with a unique array per used component.
    },
    controller: function () {

        let self = this;

        self.onSelect() { // is called when an item is selected.

        /* item selection logic */
        function validateContent(); // Validate content after selection.

            self.Content.forEach(/*...*/);
            // Here self is using the scope from the last created component
            // and not the "true" self.
            }
        }

        validateContent();               
    }
});

I expected self to refer to the scope of the component, as I see no reason for validateContent() to suddenly refer to another components' scope.

But when outputting self to the console it contains data from the last created component instead of the current one.

0

There are 0 best solutions below