JavaScript:使用this.name获取函数名

5
我正在执行以下代码。
function Person(name, age){
 this.name = name || "John";
 this.age = age || 24;
 this.displayName = function(){
  console.log('qq ',this.name);
 }
}

Person.name = "John";
Person.displayName = function(){
    console.log('ww ',this.name);
}

var person1 = new Person('John');
person1.displayName();
Person.displayName();

获得以下输出:
qq  John
ww  Person

我不明白为什么在第二个控制台中会得到 this.name = Person。

3个回答

3

这来自于Function.name,如JS MDN所解释的那样。

函数对象的只读名称属性指示函数在创建时指定的名称,或对于匿名创建的函数为“anonymous”。

function doSomething() {}
doSomething.name; // "doSomething"

2

如果你想得到所需的输出结果,请将属性name更改为name1

function Person(name1, age){
 this.name1 = name1 || "John";
 this.age = age || 24;
 this.displayName = function(){
  console.log('qq ',this.name1);
 }
}

Person.name1 = "John";
Person.displayName = function(){
    console.log('ww ',this.name1);
}

function main() {
    var person1 = new Person('John');
    person1.displayName();
    Person.displayName();
}

输出结果:
qq  John
ww  John

1

name属性返回函数声明的名称。

当您将函数作为Person.displayName()调用且尝试使用"this.name"时,它将返回函数的名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接