Issue with javascript function syntax

I am uncomfortable with the syntax in the attached screenshot.
Screenshot :

Q1: What is Person here ? Is it a variable name or function name ? I’m confused.

Q2: You know we write a function like this…

function nameOfFunction(firstname,lastname){
//some code
}

But here , there is no name to the function…is it a valid code ? Can a function exist without its name ?

Both, also an object :no_mouth:. Functions, objects, and arrays are all variable types in JavaScript. This code is actually assigning an anonymous function to a variable. Anonymous functions are pretty common in JS, you’ll most often see them used in callbacks.

function someThing(callback) {
    callback('I am data!');
}

someThing(function(someData) {
    // this is an anonymous function callback for someThing
    console.log(someData);
});

There are some benefits and caveats with writing it like this. The first 3 answers of this SO question explain it well:

The Person you have in your code is called a constructor. If you’re familiar with other languages, this is similar to a class definition.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

3 Likes

There are some limitations on creating a function that way - the other way using anonymous functions that are assigned as values to variables are far more flexible - particularly when you want to dynamically replace a function with a different function without changing how you reference it.

For example the following code works with both browsers that support JavaScript and old versions of IE that only support JScript (eg IE8).

addEvent = function(ob, type, fn ) {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
  ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, o[eProp]);
};
addEvent(ob, type, fn )
};
 
addEvent(document.getElementById('myid'),
  'click',
  myfunction);

The first function assigned to addEvent tests whether the browser supports addEventListener or attachEvent. If addEventListener then it assigns a new function to addEvent that uses a JavaScript addEventListener to add the event (the second addEvent function) and ifattachEvent then it assigns a new function to addEvent (the third function) that will work for IE8 instead. The last thing the firsat function assigned to be run as addEvent does is to run the function addEvent which by this time has been replaced by either the second or third functions (whichever version the browser supports). Subsequent calls to addEvent will call whichever of the second and third functions is still assigned to the variable without needing to retest which version the browser supports.

Three anonymous functions all assigned to the same variable in such a way as to only need to test browser support once. You couldn’t have three different functions sharing the same name if you define the functions the alternative (and less flexible) way.

Another even more common use of anonymous functions is wrapped around all modern JavaScript to avoid having it able to clash with any other script.

(function() { 
"use strict";
// all JavaScript for the script goes here
// where it is completely separate from all other scripts
}());
2 Likes

One other small point on this, it’s considered good practice to name object variables with their first letter capitalised, where other variables are all lower case - it helps differentiate them visually whilst working with the code.

[quote=“chrisofarabia, post:4, topic:211466, full:true”]One other small point on this, it’s considered good practice to name object variables with their first letter capitalised, where other variables are all lower case - it helps differentiate them visually whilst working with the code.
[/quote]

That’s interesting. My understanding of capitalising the first letter is that it was only for constructor functions.

For example:

function Person(name) {
    this.name = name;
}
var person = new Person('Joe Bloggs');

Is the expansion to also include object variables represented in any of the commonly used style guides, such as the ones found at JavaScript Style Guides And Beautifiers ?

Maybe I’ve misunderstood that then - more reading to be done I suspect.

I stand corrected - I most definitely misunderstood what I’d read. Let’s just call it a learning opportunity.

If I write

var x1={} ;

and

var x2=function(){};

What is the difference between two ? is not both of them are objects ?

Both of them are objects. The second is using a constructor function to create the object where the first has no separate constructor function.

I’m gong to disagree with @felgall here, no those are different.
x1 has a reference to a new object
x2 has a reference to an anonymous function that returns undefined

Run the following code in a terminal to see the difference.

var x1={};
var x2=function(){};

console.log(x1);
console.log(x2);
console.log(x2());

that can be an object constructor function if called with new

var x2=function() {}
var myobj = new x2();

x2 returns this which is a pointer to the object that it created - hence x2 can be an object if called with the appropriate syntax.

Anyway all functions are objects even when called directly so x2 is a reference to an anonymous object even when not used as an object constructor.

In JavaScript there is no difference between methods, functions and objects - they are ALL objects. Most variables and properties are also objects.

Ok, that makes sense and we now have all the ways that that those can be used.

var x1={};
var x2=function(){};

console.log(x1);
console.log(x2);
console.log(x2());
console.log(new x2());

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.