So I'm looking over a piece of code and I noticed this:
clickNext: function(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
Is this the same thing as this?
function clickNext(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
I haven't seen that kind of function declaration before and I confused because I tried changing the above the below and the code stopped working.
4 Answers 4
You can write function in two ways: as named function or as variable that has value as anonymous function:
var fooBoo = function () {};
function fooBoo(){}
Calling it is the same: fooBoo().
From your example it seems that you have object with one of keys with function:
var myObj = {
fooBar: function () {}
}
Now in this situation you can't replace it with function fooBar(){} as it would end up in wrong syntax:
// NOT VALID!
var myObj = {
function fooBar() {}
}
Comments
It is an object property declaration:
const thing = {
clickNext: function(e) {
...
}
}
thing.clickNext()
It's same object literal syntax as:
const person = {
name: "Jane",
age: 33
}
Comments
They are not the same things.
// this cannot be in itself
clickNext: function(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
This is part of an `Object, like:
const obj = {
value1: 5,
clickNext: function(e) {
console.log(`${e} is your function`)
},
value2: [0, 1, 2, 3, 4, 5]
}
obj.clickNext('this')
This is a function in itself:
// no comma at the end!!!
function clickNext(e) {
console.log(`${e} is your function`)
}
clickNext('this')
Comments
Below is an example of declaring functions in JavaScript, it is known as Function declaration. Keys points to note:
- We call this function as function name followed by paranthesis -
clickNext(). thiskeyword refers to global object inside function declaration, which means it refers towindowobject.function clickNext() { console.log(this) // this refers to global object window here. }
Below is an example of methods. When we have a function inside an object, it is called as method.
- We call a method using syntax of -
dummyObject.clickNext() thiskeyword refers to object in which it is declared which means in below examplethisrefers todummyObject.const dummyObject = { clickNext: function(e) { console.log(this) // this refers to dummyObject here } };
var clickNext = function(e){