Does the '@' symbol have special meaning in Javascript, Coffeescript or Jquery?
Asked Answered
O

3

42

I have some code that looks like

self = @

and then later on it's using @someMethodName or self.someMethodName

Does @ have some special meaning?

Osmunda answered 3/1, 2013 at 16:37 Comment(4)
Is that symbol existed in jquery?Spiccato
sooo..... is it a Javascript file or a coffeescript file?Rogovy
@Rogovy it's a coffeescript file, but presumably you could use that if Javascript had defined it.Osmunda
See https://mcmap.net/q/48458/-what-characters-are-valid-for-javascript-variable-namesZondra
C
71

@ is not a valid character for a javascript identifier. Identifiers may only contain $, _, digits and letters.

In coffeescript, @ means this.

CoffeeScript has a few nice features related to the this keyword. First, CoffeeScript uses the @ symbol as shorthand for this.. For example, @foo is equivalent to this.foo. Second, if you use the @ symbol in the parameters of a function, CoffeeScript will automatically assign those values as properties of the object.

Edit: As far as jQuery is concerned, the same identifier rules as javascript apply since jQuery is just javascript. For other uses of @ in jQuery, see this question or the docs.

Cockleshell answered 3/1, 2013 at 16:40 Comment(2)
It's worth adding that @foo means this.foo in CoffeeScript.Deluna
It may also be worth noting that => is pretty freaking confusing when you're trying to read someone else's CoffeeScript, imho.Olympus
R
22

@ is shortcut for this in coffeescript

So

self = @

is coffeescript for:

var self = this;
Rheims answered 3/1, 2013 at 16:40 Comment(1)
which nowadays, for safety, should be const self = @ ;)Duke
E
1

Since the design of CoffeeScript a couple of years have passed and not everything which was proposed in CoffeeScript made it into ECMA script. Instead of being used as a shortcut for this, it's proposed to be used for decorators.

Emissary answered 2/7, 2020 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.