Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 17, 2021 02:53 am GMT

JavaScript question Day 7

What's the output ?

function Person(firstName, lastName) {  this.firstName = firstName;  this.lastName = lastName;}const member = new Person('Lydia', 'Hallie');Person.getFullName = function() {  return `${this.firstName} ${this.lastName}`;};console.log(member.getFullName());
  • A: TypeError
  • B: SyntaxError
  • C: Lydia Hallie
  • D: undefined undefined

Answer: A

In JavaScript, functions are objects, and therefore, the method getFullName gets added to the constructor function object itself. For that reason, we can call Person.getFullName(), but member.getFullName throws a TypeError.

If you want a method to be available to all object instances, you have to add it to the prototype property:

Person.prototype.getFullName = function() {  return `${this.firstName} ${this.lastName}`;};

Original Link: https://dev.to/soorajs98/javascript-question-day-7-50ai

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To