1

I have a constructor function defined as follows:

function Person(fname, lname) {
  this.firstName = fname;
  this.lastName = lname;
  this.printName = function(fname, lname){
      console.log("Name: " + this.firstName + " " + this.lastName);
  }
}

Now, I can use the new keyword to create an object from my constructor function and call the "printName" method to print the created "Person" object firstName and lastName:

const p = new Person("John", "Doe");
p.printName(); // output: 'Name: John Doe'

I can also use the built-in javascript .call method with my constructor function to create a new object as follows:

Person.call({}, "John", "Doe");

Here's my question: How can I call the "printName" method in this case?

2
  • 1
    Person.call doesn't create a new object. The object literal {} does. And it's only a plain object, not a Person instance, which is the reason why you should use new instead. Commented Jun 17, 2019 at 21:17
  • Person.call({}, "John", "Doe").printName() ? I dont get the question ... Commented Jun 17, 2019 at 21:26

1 Answer 1

2

Since you're calling the method directly, you would need to return a value from it:

function Person(fname, lname) {
  this.firstName = fname;
  this.lastName = lname;
  this.printName = function(){
      console.log("Name: " + this.firstName + " " + this.lastName);
  }
  return this;
}

Then you can call the result, like:

Person.call({}, "John", "Doe").printName();
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.