EvaKaf
EvaKaf

Reputation: 45

Using Call method with Constructor Function

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?

Upvotes: 1

Views: 56

Answers (1)

Steve H.
Steve H.

Reputation: 6947

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

Upvotes: 2

Related Questions