Javascript: getting function name using this.name

I am executing the following code

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();

get the following output:

qq  John
ww  Person

I do not get how I get this.name = Person in the second console

+4
source share
3 answers

This comes from Function.name, as described in JS MDN

The object name property only for a function object indicates that the function name specified when it was created, or "anonymous" for functions, was created anonymously.

function doSomething() {}
doSomething.name; // "doSomething"
+2
source

If you want the desired result, change the property nametoname1

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();
}

Output:

qq  John
ww  John
+1
source

name .

Person.displayName(); "this.name".

+1

Source: https://habr.com/ru/post/1691218/


All Articles