Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript : getting function name with this.name

I am executing 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();

getting following output :

qq  John
ww  Person

I am not getting how am getting this.name = Person in second console

like image 347
Javed IN Avatar asked Dec 22 '17 06:12

Javed IN


3 Answers

That comes from Function.name as explained in the JS MDN

A Function object's read-only name property indicates the function's name as specified when it was created, or "anonymous" for functions created anonymously.

function doSomething() {}
doSomething.name; // "doSomething"
like image 152
Adelin Avatar answered Oct 17 '22 18:10

Adelin


If you want to get the desired output, change the property name to 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();
}

The output :

qq  John
ww  John
like image 42
Jayram Kumar Avatar answered Oct 17 '22 17:10

Jayram Kumar


The name property returns the name of a function statement.

When you are calling function as Person.displayName(); & try to use "this.name". it will return name of the function

like image 28
Bhaurao Birajdar Avatar answered Oct 17 '22 16:10

Bhaurao Birajdar