8

Suppose I have an 2 objects x and y. The details are written in the code below.

let x = {
  publish: function() {
    console.log(this.publish.name);
  }
};
let y = {};
y.publish = function() {
  console.log(this.publish.name);
};
x.publish();
y.publish();

I was getting difference in the outputs calling x.publish() and y.publish(). The former returned the name of the function while the latter returned empty. Can anyone explain why is this happening, and is there any other possible way I can retrieve the function name in latter(WITHOUT HARDCODING). I am using NodeJs version 8.

Yogesh Patel
  • 818
  • 2
  • 12
  • 26
Bhavya Dhiman
  • 237
  • 2
  • 14
  • 3
    Because the second one is anonymous function hence it has empty string in name property. – Manish Jangir Dec 11 '18 at 10:10
  • 2
    @ManishJangir - I don't think that explains it. Both functions here are technically "anonymous", because they're defined with an anonymous function expression: `function() {...}` - when you could instead have used `function my_func() {...}` Having just looked at the MDN page for the function `name` property: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name - it seems that for object properties the `name` does refer to the property name. But this doesn't explain why it doesn't work for `y`. (And why it is an empty string rather than `"anonymous"`.) – Robin Zigmond Dec 11 '18 at 10:21

3 Answers3

0

Since the function in the second case doesn't have any name associated with it so you get empty string.

let x = {
  publish: function() {
    console.log(this.publish.name);
  }
};
let y = {};
y.publish = function() {
  console.log(this.publish.name);
};

let z = {};
z.publish = function hello() {
  console.log(this.publish.name);
};
x.publish();
y.publish();
z.publish();
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

In your second case y.publish, you're assigning a variable identifier to the function but not giving it a name. that would be y.publish = function publish()

Prodigle
  • 1,757
  • 12
  • 23
0

Basically any time an anonymous function expression appears on the right-hand side of something like an assignment or initialization, like:

var boo = function() { /*...*/ };
(or it could be let or const rather than var), or

var obj = {
    boo: function() { /*...*/ }
};

or

doSomething({
    boo: function() { /*...*/ }
});

(those last two are really the same thing), the resulting function will have a name (boo, in the examples).

There's an important, and intentional, exception: Assigning to a property on an existing object:

obj.boo = function() { /*...*/ }; // <== Does not get a name

Search for SetFunctionName on the following:

1. Property initializer semantics

2. Assignment Operator Semantics

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75