Reputation: 43
I'm reading the book "Secret JavaScript Ninja". The book says that if you assign an anonymous function to a variable, if you refer to the name property, it will not contain the name of the variable, but if I refer to this property, I see it.
How is this possible?
var canFly = function(){return true}
console.log(canFly.name)
However, if I declare the function via a property of the window object, the function name is missing
window.isDeadly = function(){ return true}
console.log(window.isDeadly.name === '')
Why the first statement I described from the book, was not appropriate?
Upvotes: 1
Views: 91
Reputation: 3302
According to the MDN page about Function.prototype.name:
Variables and methods can infer the name of an anonymous function from its syntactic position (new in ECMAScript 2015).
It seems that declaring a function in a property-assignment of the form obj.prop = ...
does not qualify for automatic function name definition:
var foo = {};
foo.prop = function() { return true; };
console.log(foo.prop.name); // ""
You are probably reading the first edition of "Secrets of the JavaScript Ninja" (which is from 2008). This edition is about an old JavaScript version which is obsolete by now. At that time even assignments to variables did not cause automatic function name definition (at least that was not specified). I strongly suggest you to get a copy of the second edition (2016) which also includes features introduced in ES2015.
Upvotes: 3
Reputation: 36
its because you technically didn't assign the function a name. what you are doing in the bottom snippet is declaring & assigning window.isDeadly to an anonymous function. See below for how to achieve what you were attempting.
var foo = function() {
};
window.foo = foo;
console.log(foo.name === '');
Upvotes: 0