oxc/no-this-in-exported-function
Disallow this in exported functions
After import { save } from "./store", a call to save() has no object in front of it, so this is undefined and this.items throws. With import * as store, store.save() sees the module's exports as this, but a bundler can turn that into a plain save() call, and then the same code only breaks in the bundle.
The rule checks export function, export default function, and functions listed in export { name }. An arrow function inside one of them uses the same this, so it's checked too. export const save = function () {} and export default save aren't checked.
Configure#
Off by default. To turn it on:
[lint.rules]
"oxc/no-this-in-exported-function" = "error" # or "warn"Examples#
export function save(item) {
thisthis should not be used in exported functions.items.push(item);
}function save(item) {
return () => thisthis should not be used in exported functions.items.push(item);
}
export { save };const items = [];
export function save(item) {
items.push(item);
}Pass the object as an argument if the function works on more than one:
export function save(store, item) {
store.items.push(item);
}A regular function or a class inside the exported function has its own this:
export function createStore() {
return {
items: [],
save(item) {
this.items.push(item);
},
};
}When not to use it#
A function you export so it can be attached to an object or called with .call() uses this on purpose. The rule reports it even if it declares a TypeScript this parameter.