You have to be careful with the second example, the this
keyword will refer to the Global object if you invoke the function without the new
operator, and by looking at your return value, seems that you aren't trying to make a constructor function.
I think you need to know how the this
keyword (the function context) works:
The this
keyword is implicitly set when:
1- When a function is called as a method (the function is invoked as member of an object):
obj.method(); // 'this' inside method will refer to obj
2- A normal function call:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
3- When the new
operator is used:
var obj = new MyObj(); // this will refer to a newly created object.
And you can also set the this
keyword explicitly, with the call
and apply
methods:
function test () {
alert(this);
}
test.call("Hello world"); // alerts 'Hello world'
Now, the difference between the b
function of your two examples, is basically that in the first snippet, b
is a function declaration, in your second example b
is a function expression.
Function declaration are subject to hoisting, and they are evaluated at parse time, on function expressions are defined at run-time.
If you want more details of the differences between function declarations and function expressions, I leave you some resources:
And BTW, you don't need the semicolon after function declarations.