在JavaScript中调用对象内的函数名称(NodeJs)

Bha*_*man 8 javascript node.js

假设我有2个对象xy.详细信息写在下面的代码中.

let x = {
  publish: function() {
    console.log(this.publish.name);
  }
};
let y = {};
y.publish = function() {
  console.log(this.publish.name);
};
x.publish();
y.publish();
Run Code Online (Sandbox Code Playgroud)

我的输出调用x.publish()y.publish().前者返回函数的名称,而后者返回空.任何人都可以解释为什么会发生这种情况,还有其他任何可能的方法我可以在后者中检索函数名称(WITHOUT HARDCODING).我正在使用NodeJs版本8.

Cod*_*iac 0

由于第二种情况下的函数没有任何与之关联的名称,因此您会得到空字符串。

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();
Run Code Online (Sandbox Code Playgroud)