What is the difference between these two way of defining a method?
var Todo = {};
Todo.abc = function(){
}
and
function abc(){
}
What is the difference between these two way of defining a method?
var Todo = {};
Todo.abc = function(){
}
and
function abc(){
}
The first is an anonymous function expression, stored in the abc
property. These are not hoisted.
The second is a function declaration. It has a name
property and it is hoisted.
From MDN:
The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions.
Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you define them:
First is a Todo property, second is a global function. In fact, in order to call the first one you have to write
Todo.abc();
Note that Todo.abc = 'Hello' will overwrite instance property.