0

我正在与一个在 jQuery 中声明变量时从不使用 var 的开发人员合作。就像是:

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

jQuery 对此没有任何问题,而且他已经这样做了一段时间。我一直使用var:

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

我们遇到了一个问题,美元符号引起了问题(那是一年前,所以我不记得这个问题了)。

有谁知道或了解两者之间的区别以及为什么一个更好或应该使用另一个?

我做了一些谷歌搜索,但他们都在谈论var $x; vs var x;

4

4 回答 4

4

使用美元符号不能替代var. $在变量名中与任何其他字符相同。$通常添加到包含 jQuery 对象的变量之前。IE:

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

相对:

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

所以它主要用于区分。它对脚本的执行没有任何影响。

var$参考完全无关。实际上,在全局范围内:

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

是相同的

$el = $('#id')
于 2014-03-11T14:50:41.473 回答
0

没有var全局定义的变量通常不会导致问题,当使用具有相同名称但不同函数/字符串的变量时,您应该在另一个范围内使用 var 声明它,以防止它覆盖原始全局变量。

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
于 2014-03-11T15:01:07.790 回答
0
$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;
于 2014-03-11T14:52:35.510 回答
0

美元符号没有做任何特别的事情,它只是变量名的一部分。

声明变量而不var 生成全局变量

于 2014-03-11T14:50:39.620 回答