In jQuery what is the difference between using the dollar sign VS var?

你说的曾经没有我的故事 提交于 2019-12-13 07:45:34

问题


I'm working with a developer that never uses var when declaring variables in jQuery. Something like:

$x = "hello";
$y = "world";
$a = x + " " + y;

jQuery doesn't have a problem with this and he's been doing this for awhile. I've always used var:

var x = "hello";
var y = "world";
var a = x + " " + y;

We have run into one issue where the dollar sign caused an issue (it was a year ago so I can't recall the issue).

Does anyone know or have info on the difference between the two and why one is better or should be used over the other?

I've done some Google searching but they all talk about var $x; vs var x;


回答1:


Using a dollar sign isn't a replacement for var. $ in a variable name is the same as any other character. $ is often prepended to variables that contain a jQuery object. I.E:

var el = document.getElementById('id');

Versus:

var $el = $('#id');

So it's used primarily to differentiate. It makes no difference to the execution of your script.

var and $ in a reference are completely unrelated. In fact, in the global scope:

var $el = $('#id');

is the same as

$el = $('#id')



回答2:


The dollar sign is not doing anything special, it is just part of the variable name.

Declaring variables without var makes a global variable.




回答3:


$x = "hello";
$y = "world";
$a = x + " " + y;

This code is wrong. x and y is undefined.

Actually $x is not declaring x. $x is the same with var $x not with var x

$x is a variable name such any other one

You could write:

    x = "hello";
    y = "world";
    a = x + " " + y;

And it would be the same thing as:

    $x = "hello";
    $y = "world";
    $a = $x + " " + $y;



回答4:


having no var for variable defined globally will generally not cause an issue, when using a variable with the same name but different function/string you should declare it with var in another scope as to prevent it over riding the original global one.

http://jsfiddle.net/YWK7T/1/

$x = "hi#1";
alert($x); //alerts hi#1 as $x is declared globally
function hi(){
    var $x = "hi#2";
    alert($x); 
}
hi(); //alerts hi#2 as $x within the function scope is hi#2
alert($x); //alerts hi#1 the previous $x was defined within the scope.
function hi3(){
    $x = "hi#3";
}
hi3(); //replaces global vairiable $x to hi#3
alert($x); //alerts hi#3


来源:https://stackoverflow.com/questions/22329185/in-jquery-what-is-the-difference-between-using-the-dollar-sign-vs-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!