An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
July 17, 2021 02:53 am GMT
Original Link: https://dev.to/soorajs98/javascript-question-day-7-50ai
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To