开发者

JQuery : What is the difference between "var test" and "var $test" [duplicate]

开发者 https://www.devze.com 2023-01-01 02:06 出处:网络
This question already has answers here: Why would a JavaScript variable start with a dollar sign? [duplicate]
This question already has answers here: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 answers) Closed 8 years ago.

what is the difference between these statements? I know that "var $test" declar开发者_如何学Goes a jquery variable, but what is the difference of a jquery variable with a general javascript variable ?


$test is a convention used to indicate that this variable is a jQuery object and you can call the standard functions on it while test could be a standard DOM element and you cannot call the val function on it for example.

For example:

var $test = $('#someId');
var test = document.getElementById('#someId');

You can do $test.text(); but you cannot do test.text();


Nothing. No difference. $ is a valid character in a JavaScript identifier but has no special meaning. In fact, in the ECMAScript 3 specification in section 7.6 it states that

The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.

... although events have now probably rendered that recommendation obsolete. Indeed, the recent ECMAScript 5 spec omits the final sentence.


there is no difference between var $test and var test. but its always good to know what kind of data is in your variable: (for example if someone else just want to modify a function in your code without having to read, or have to console.log your vars to know whats in it)

here some examples:

var arrTest = [1, 2, a, b, c], //Array
objTest = {test: 1, test2: 2}, //Object
strTest = "test", //String
intTest = 4, //integer
$test = $("#test") //jqueryObject

but it would also work like this

var Test1 = [1, 2, a, b, c], //Array
test2 = {test: 1, test2: 2}, //Object
Test3 = "test", //String
Test4 = 4, //integer
$test = $("#test") //jquery Object

i think what confuses you is the $() form jquery.

Jquery is basically a function set on the variable name $:

var $ = function(e){ // the jquery magic }

but you can still use $somethingelse as variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消