Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object Method returns the code as a string

I’ve just started to learn javascript and can’t seem to call an object method properly. I’ve even copy pasted the code from here to try to understand my mistake but it just returns the code as a string. My code:

function greetings(name){
    document.getElementById('someText').innerHTML = 'Hello' + ' ' + name;
}

const person = {
    firstName: "John",
    lastName: "Doe",
    id: 5566,
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
  

  greetings(person.fullName);
<div id="someText"></div>

And the result:

Hello function() { return this.firstName + " " + this.lastName; }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to call the method, which will return a string of the person’s name, and then that will be passed to the greetings function.
Without the () the method is not executed and the method itself is passed to the greetings function.
Since it is treated as a string in the function you get the toString() method being called on the function which results in the function code itself.

function greetings(name){
    document.getElementById('someText').innerHTML = 'Hello' + ' ' + name;
}

const person = {
    firstName: "John",
    lastName: "Doe",
    id: 5566,
    fullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
  

  greetings(person.fullName());
  console.log(person.fullName.toString());
<div id="someText"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading