`function go()` vs `go = function()`
I ran into what seems to be a silly issue with some Javascript:
go = function () {
alert("Go!");
}
$(function () {
go();
});
When the page loads I get an error:
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .N开发者_JS百科ET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; .NAP 1.1) Timestamp: Thu, 17 Mar 2011 20:18:03 UTC
Message: Object doesn't support this property or method Line: 1 Char: 1 Code: 0 URI: http://localhost:61710/Scripts/number.js
When I change the go
initializer to this:
function go() {
alert("Go!");
}
...everything works just fine.
What am I missing? Also, is there a reason to use one form of function initializer over the other?
Edit: I get this error when I run the code in an instance of IE8 using the built-in Visual Studio web server (Start without Debugging). When I run the code in a separate instance of IE8 without Visual Studio, it works just fine. Perhaps Visual Studio forces IE to use stricter JS compiler settings?
You should declare the variable first:
var go = function () {
alert("Go!");
}
One reason to use this form is that it can help and avoid polluting the global namespace with your functions (see an example of this notion here).
The difference (and may help you decide which is better over another) is that
go = function () {
alert("Go!");
}
is defined at parse-time whereas
function go() {
alert("Go!");
}
is defined at run-time.
P.S., it works for me, however you may need to do:
var go = ...
rather than
go = ...
work fine for me:
http://jsfiddle.net/vEKgX/
although try this instead:
var go = function () {
alert("Go!");
}
$(go);
精彩评论