swc icon indicating copy to clipboard operation
swc copied to clipboard

Arrow functions inside of getters/setters on object literals use the wrong `this`

Open KyleDavidE opened this issue 8 months ago • 0 comments

Describe the bug

Arrow functions inside of getters use the this context of the surrounding context, rather than of the getter.

Input code

const myObj = {
  get foo(){
    return () => this;
  },
};

const fn = myObj.foo;

// should be true
console.log(fn() === myObj);

Config

{
  "jsc": {
    "parser": {
      "syntax": "ecmascript",
      "jsx": false
    },
    "target": "es5",
    "loose": false,
    "minify": {
      "compress": false,
      "mangle": false
    },
  },
  "module": {
    "type": "es6"
  },
  "minify": false,
  "isModule": false
}

Playground link (or link to the minimal reproduction)

https://play.swc.rs/?version=1.5.16&code=H4sIAAAAAAAAAy2MQQ6EIBAE7yT8oY%2BQbPQBhv3C%2FkEd1A3LJDAcNsa%2Fi%2BhterqrJo5Z8Pt%2Fxi8cdq2AhQSe2diWgERSUoSxcG%2FIuuXh%2Bh8vrY56aTU1hY%2BVb56uwq3oe%2BSVS5gxEiQVurccqAu8GB8vpXsoO5x3oIfBiwAAAA%3D%3D&config=H4sIAAAAAAAAA2WPSw7CMAxE95wi8potLLgDh7CCW6XKT3aQiKrenTSfAmJj2TPPHnk9KQWLaLiptbRliMhCfMxFkewTvooCpB2KZhMTnIe7yG5NaIWqtDUHEvJMqW7JpeNgQxAaeNec8WbK34E6uMgk8gvuKPrZ0n9cLeDC41nd%2FknKkVr%2BFT7QSDsug5H72Gx3tzcE4cPeFgEAAA%3D%3D

SWC Info output

No response

Expected behavior

This is bound inside of the getter

var myObj = {
    get foo () {
        var _this = this;
        return function() {
            return _this;
        };
    }
};

// ...

Actual behavior

This is bound outside of the getter

var _this = this;
var myObj = {
    get foo () {
        return function() {
            return _this;
        };
    }
};

// ...

Version

1.5.16 (repros on every version I tried, including all of 1.5.x)

Additional context

No response

KyleDavidE avatar May 28 '24 22:05 KyleDavidE