开发者

JavaScript variable declaration

开发者 https://www.devze.com 2023-02-15 15:14 出处:网络
What\'s the开发者_JAVA百科 difference between following types of var declaration in JavaScript? $x

What's the开发者_JAVA百科 difference between following types of var declaration in JavaScript?

$x

var x

var $x


$x and x are simply two different variable names. Like var x and var y. Simply using $x is an implied declaration, except that if $x exists in a higher scope, you'll use it. declaring var $x sets up a new $x in the current scope which avoids conflicts with any other $x at a higher scope.


No difference except for scope. $x is just a variable name like x. var creates variables in a local scope, otherwise they are global.

This has nothing to do with jQuery, really.


If you use $x without declaring it, you are implicitly creating a global variable called $x. var x and var $x each create a variable in whatever function (or global scope) you're in, called x and $x, respectively. Neither has anything to do with jQuery.


Nothing. I find it good practice, however, to precede variable names with a $ if it returns a jQuery object and without if it returns a DOM object or other type (string, etc.)

The term 'var' is useful for determining scope. Always use 'var' on first declaration, or on anytime you need a variable to be local in scope.

0

精彩评论

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