0

The global variable selected is called like this.selected and always returns the correct value.

but when called from a dynamically created function its returns unknown

onClick: function(val){
            for (i = 0; i < 
positions[this.selected].SHC.length; i++){
                var tag = 
positions[this.selected].SHC[i];
                var tagEl = 
document.createElement('p');

                console.log(this.selected) // RETURNS CORRECT VALUE
                tagEl.onclick = function(){
                    console.log(this.selected) // RETURNS UNKNOWN
                    for (j = 0; j < positions[this.selected].SHC.length; j++){

                        if (positions[this.selected].SHC[j] == this.innerHTML){
                            positions[this.selected].SHC.splice(j,1);
                        }
                    };
                ;}
                tagEl.textContent = tag;
                document.getElementById("uldshtags").appendChild(tagEl);
            }
        },

How can I make the global variable also available for functions created dynamically.

MK01111000
  • 468
  • 1
  • 6
  • 13
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – VLAZ Jun 12 '19 at 07:52
  • The second `this.selected` will have `this` set as `tagEl`, not whatever the first `this` would be. – VLAZ Jun 12 '19 at 07:53
  • Thanks for explaining that. How do I get the global variable in this case? – MK01111000 Jun 12 '19 at 07:56
  • 1
    Either do something like `self = this` before the new function and use `self.selected` or use `.bind` to set the value of `this` permanently for the function. – VLAZ Jun 12 '19 at 07:57
  • That solved it, Thanks! – MK01111000 Jun 12 '19 at 08:03

1 Answers1

1

Declare a variable and assign 'this' before 'onclick' function and use that vaiable inside 'onclick'.

      onClick: function (val) {
    for (i = 0; i <
        positions[this.selected].SHC.length; i++) {
        var tag =
            positions[this.selected].SHC[i];
        var tagEl =
            document.createElement('p');
        var that = this;
        console.log(this.selected) // RETURNS CORRECT VALUE
        tagEl.onclick = function () {
            console.log(that.selected) // RETURNS UNKNOWN
            for (j = 0; j < positions[that.selected].SHC.length; j++) {

                if (positions[that.selected].SHC[j] == this.innerHTML) {
                    positions[that.selected].SHC.splice(j, 1);
                }
            };

        }
        tagEl.textContent = tag;
        document.getElementById("uldshtags").appendChild(tagEl);
    }
}