Declaring variables javascript
This question already has an answer here:
I use this convention too keep track of if a variable is storing a JQuery object. So say the function getJQueryObject()
returns a JQuery object and I want to store it.
ie:
var $myJQobj = getJQueryObject();
Makes it clear that $myJQobj
is a JQuery object unlike ie
var myStr = "hello";
The $
as the first character in the identifier doesn't have any special meaning, you aren't invoking a method like $()
, it's just a perfectly valid identifier in JavaScript. But the factthat the $
is used in JQuery makes what I was talking about before even clearer.
Is there a reason for this?
Hard to say. Maybe he came from a PHP background where $
prefixes the variables. Maybe he's a jQuery addict. Who knows? You'd have to ask him. That aside, $
is a perfectly legitimate character to use in a JavaScript variable name but as you noted, it could cause issues with jQuery. But that's why jQuery offers a noConflict()
option.
$
is a valid variable character, and in PHP all variables start with it. It's possibe that that particular developer uses $
as a "flag" to mean "this is a variable". It has no special meaning.
上一篇: 使用Visual Studio调试TypeScript代码
下一篇: 声明变量javascript