What is the difference between these code?
1- move : function(a,b){
.
.
.
}
2- function move(a,b){
.
.
.
}
I know second part is a function but I don't know any thing about first part? Can you answer me about it?
What is the difference between these code?
1- move : function(a,b){
.
.
.
}
2- function move(a,b){
.
.
.
}
I know second part is a function but I don't know any thing about first part? Can you answer me about it?
Your first example is invalid JavaScript by itself. You're probably seeing it as part of a very large object initialization in a library somewhere; i.e.:
var Library = {
// ...lots of lines
move: function(a, b) { /*...*/ },
// ...lots more lines
};
In that case it's the same :
you see in any property initialization. Same as this:
var object = {
foo: 1,
bar: 2
};
The first one is part of an object (or should be) and defines a function as a property of that object, whereas the second defines the function move()
in the current scope.
(1)move
is usually a property, and you are assigning a function to that property. It is part of other code and not stand alone. Example:
var myObj = {
sayHello: function() {
console.log('Hello');
},
sayBye: function() {
console.log('Bye');
}
}
You can then use it like this:
obj.sayHello();
obj.sayBye();
(2) as you say, it is simply a function named move
You could therefore also 'combine' both:
function myHello(){
console.log('Hello');
}
var myObj = {
sayHello: myHello,
sayBye: function() {
console.log('Bye');
}
}
Colons are generally used to define properties in objects, e.g
obj = {
myProp: "String",
myFunc: function() {
console.log('hello');
}
}
console.log(obj.myProp);
obj.myFunc();
They are additionally used in ternary operators, e.g.
x = ( y >= 2 ) ? "greater" : "not greater";
is the same as
if (y >= 2)
{
x = "greater";
}
else
{
x = "not greater";
}
where the ?
is saying "if true then", and the :
is the same as "else".
Its essentially a difference between function expression and function declaration. You can read about this in detail on MDN
tl:dr; One gets interpreted at load time and other gets interpreted at runtime.
Note that functions in Javascript are themselves objects (and thus variables).
So these all accomplish the same thing:
1
var some_object = {};
some_object.do_something = function () {
// function code
};
2
var some_object = {
do_something: function () {
// function code
}
}
3
var some_object = {};
var some_function = function () {
// function code
};
some_object.do_something = some_function;
4
var some_object = {};
function some_function () {
// function code
};
some_object.do_something = some_function;
Only difference between those, which is probably irrelevant to you, is that 3 and 4 have a function called some_function
in the outer scope. Otherwise they are identical.