标签云

微信群

扫码加入我们

WeChat QR Code

在JavaScript函数的声明[复制]

Possible Duplicate:
Javascript: var functionName = function() {} vs function functionName() {}

What's the difference between these two ways of declaring a function?

function someFunc() { ... }

var someFunc = function() { ... }

I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.


Duplicate of stackoverflow.com/questions/336859/…

2018年06月19日09分16秒

The main part of this is unclear and doesn't have anything to do with the question.

2018年06月19日09分16秒

Maybe but in the other hand, spongebob is speaking to you

2018年06月19日09分16秒

I don't agree that the first form is a more recognized syntax and that the second form. They are just different forms, btoh of which are in common use. Also, named function expressions (which is what you're using in the last example) have odd behaviour in IE. See the following article: yura.thinkweb2.com/named-function-expressions

2018年06月20日09分16秒

You have some misconceptions here: first, there is a difference between named and anonymous functions in JavaScript, as you can see by calling toString on a function. Second, while it is true that a function declaration does add a property to the current varibale object, that's only the global object (aka window in browsers) in global code (as opposed to inside a function, for example). As a result, your third paragraph is completely false. (continued...)

2018年06月19日09分16秒

... Third, there's a difference in when the function is assigned to the variable object. Functions created by a function declaration (e.g. function test() {}) may be used in code that appears before it, which is not true of functions declared by a function expression (e.g. var test = function() {};)

2018年06月19日09分16秒

That is not what reported in "JavaScript: The Definitive Guide", which clearly states "When the JavaScript parser encounters a function definition, it parses and stores (without executing) that comprise the body of the function. The it defines a property (in the call object if the function definition is nested with another function; otherwise, in the global object) with the same name as the function tohold the function.

2018年06月20日09分16秒

I removed the part that was not correct. The point is that in both the cases the JavaScript interpreter creates a property; technically, as asked from the OP there are not differences.

2018年06月19日09分16秒

I'm not sure which of my points you disagree with. Which one is it? Regarding your answer as it is now, my first point still stands. It seems like my second point also still stands since a function declaration inside a function body does not become a property of the global object. My third point still stands because it points out a difference between function declarations and function expression that your answer doesn't mention.

1970年01月01日00分03秒