0

I want to add multiple properties to "Person" class. This instance will be called by getDetails() method. So I easily can pass an array of values to my objects (variable), ex. var john = new Person("John Doe", "32", "Web Developer");.

function Person(name, age, occupation) {
  this.name = name;
  this.age = age;
  this.occupation = occupation;
}
Person.prototype.getDetails = function () {
  return this.name;
  return this.age;
  return this.occupation;
};
var john = new Person("John Doe", "32", "Web Developer");

document
  .getElementById('demo')
  .innerText = john.getDetails();
<h2>JavaScript Class Method</h2>

<p>How to define and use a Class method.</p>

<p id="demo"></p>

1
  • 6
    The "adding properties" part is correct. Do console.log(john) and you will see that too. The way you are inspecting your data is incorrect. Since a function can only return once, anything after return this.name; is ignored. Commented Aug 31, 2021 at 7:12

1 Answer 1

1

Note that after return all code is unreachable!

So you need to concatenate the properties and combine as a one string like this:

function Person(name, age, occupation) {
  this.name = name;
  this.age = age;
  this.occupation = occupation;
}
Person.prototype.getDetails = function () {
  return this.name + " " + this.age + " " + this.occupation;
};
var john = new Person("John Doe", "32", "Web Developer");

document
  .getElementById('demo')
  .innerText = john.getDetails();
<h2>JavaScript Class Method</h2>

<p>How to define and use a Class method.</p>

<p id="demo"></p>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.