Javascript:使用this.name获取函数名称

问题描述 投票:4回答:3

我正在执行以下代码

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 =第二个控制台中的人

javascript closures
3个回答
2
投票

这来自Function.name,如JS MDN所述

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

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

1
投票

如果要获得所需的输出,请将属性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”。它将返回函数的名称

© www.soinside.com 2019 - 2024. All rights reserved.