Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule proposal: no-this-in-object-expression #2431

Open
axetroy opened this issue Aug 21, 2024 · 3 comments
Open

Rule proposal: no-this-in-object-expression #2431

axetroy opened this issue Aug 21, 2024 · 3 comments

Comments

@axetroy
Copy link
Contributor

axetroy commented Aug 21, 2024

Description

It is unsafe to use this in an object's properties

It may contain potential bugs

const obj = {
  name: 'foo',
  foo() {
    return this.name
  }
}

obj.foo() // 'foo'

const foo = obj.foo;

foo() // ''

Fail

const obj = {
  name: 'foo',
  foo() {
    return this.name
  }
}

Pass

const obj = {
  name: 'foo',
  foo() {
    return obj.name
  }
}

Proposed rule name

no-this-in-object-expression

Additional Info

No response

@fisker
Copy link
Collaborator

fisker commented Aug 21, 2024

I'm not sure about this, it common pattern, and most time, it mean to used as method call, the problem is not how the object defined, but how it's used.

Wish we have bind operator.

@fregante
Copy link
Collaborator

I don’t think it’s any less safe than using it in classes. A class method obj.foo is indistinguishable from an object property obj.foo, so in both cases one has to be aware of this.

There’s some merit to avoiding this in objects, I think, but then there’s also situations where people might want to use this and explicitly bind the function, like obj.getName.call(user)

I can’t say I used any of these patterns in a very long time though.

@fisker
Copy link
Collaborator

fisker commented Sep 8, 2024

How about no-method-destructuring?

Forbid destructure a method without .bind()

// Bad
const foo = obj.foo;

// Good
const foo = obj.foo.bind(obj)

// Good
const foo = (...args) => obj.foo(...args)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants