Hanfei Sun
Hanfei Sun

Reputation: 47051

Why does this syntax of $ for jQuery and Backbone.js work?

For example, demo_view is an instance of Backbone.View, from this tutorial, this usage is recommended..

demo_view.$el.html()

As I understood, $ in jQuery is a function that should be used with parentheses, e.g. -> $("#id"), but why it can be used in demo_view.$el without a parentheses? Does anyone have ideas about this?

Upvotes: 2

Views: 68

Answers (3)

dchhetri
dchhetri

Reputation: 7136

The reason why they use $el is to denote that the el element is a jquery object. It is purely for readability. Appending '$' before a variable identifier is kind of like a notation that denotes that the variable is a jquery object.

Upvotes: 2

Joseph
Joseph

Reputation: 119847

Both $ and _ are valid symbols that can be used in variable names and property names. The convention by some develoepers is to use $ to indicate that the property or variable is a jQuery object and not some ordinary object or value. Thus you can readily tell that it is a jQuery object and use jQuery methods without doubt.

Upvotes: 0

Antoine
Antoine

Reputation: 2807

It's also a symbol which can be used to name a simple variable, it belongs to the set of allowed characters for naming variables in javascript.

In jQuery, $ is used to name a function (it's a shorthand for the variable jQuery actually) but they could have chosen any letter of the alphabet or any other valid variable name.

Upvotes: 3

Related Questions