-1

I've asked this in the past but still not understanding why my this is always window and not the calling object.

on the page there is button control:

<input type="button" value="Press Me" id="buttonPressMe" @click="pressMeClicked" />

This is the component and under methods is where I have functions:

enter image description here

enter image description here

pressMeClicked() is the function that gets called:

pressMeClicked: () => {
    console.log(this.el)
    var dd = this;
    console.log('pressMeClicked');
}   

The problem is this is not the component object in the pressMeClicked() function. It's always the window object. The code below shows how I add an event listener to the element. And either of the two options I used does call the pressMeClicked function. The only problem is that this is not the component obj but window:

const funcBind = function(obj, method, args = []){
    return function(){
        return method.apply(obj, args);
    }
}

const funcProcess = (component, elements) => {

    const fn = component.methods['pressMeClicked'];
    const methodCall = funcBind(component, fn);
    const elem = component.selector('#buttonPressMe');

    elem.addEventListener('click', () => {
        // Tried this
        fn.bind(component)()
        // Tried this also
        methodCall();
    }       
}

When I step into the function methodCall(), obj is the component.

Any help would greatly be appreciated

adviner
  • 3,295
  • 10
  • 35
  • 64
  • You can't rebind an arrow function context. It's bound to whatever context it was defined in, that's kind of the idea. Try with `pressMeClicked: function(){ console.log( this) }`. – pawel Jan 16 '18 at 21:20
  • I have tried it using elem.addEventListener('click', function(){} also and I get the same result – adviner Jan 16 '18 at 21:23
  • Because neither `fn.bind` nor `funcBind( component, fn)` will work when `fn` is an arrow function. – pawel Jan 16 '18 at 21:25
  • Possible duplicate of [Typescript "this" inside a class method](https://stackoverflow.com/questions/16157839/typescript-this-inside-a-class-method) – cнŝdk Jan 16 '18 at 21:25
  • Take a look at [**'this' in TypeScript**](https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript). – cнŝdk Jan 16 '18 at 21:26
  • Thanks pawel, I get it now. Learn something new everyday :) – adviner Jan 16 '18 at 21:28

1 Answers1

1

pressMeClicked is an arrow function, which is a non-bound function. Because of that, this will always refer to the value of this inside the lexical scope of its containing function. To fix this change the arrow function definition to a regular function (method):

// Instead of:
pressMeClicked: () => {
    // ...
}

// Do this:
pressMeClicked() {
    // ...
}

// or:
pressMeClicked: function() {
    // ...
}
JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28