jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
27 stars 4 forks source link

Class and Prototype #133

Closed jsartisan closed 2 months ago

jsartisan commented 2 months ago

Info

difficulty: easy
title: Class and Prototype
type: quiz
tags: css, html, javascript

Question

What will be output of following code:

class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello ${this.name}`);
  }
}

console.log(typeof User);
console.log(User.prototype);
console.log(User.prototype.constructor);
console.log(Object.getOwnPropertyNames(User.prototype));

This challenge tests your knowledge about how "class" syntax actually do under the hood.

Solution

function
{
  constructor: [Function: User],
  greet: [Function: greet]
}
[Function: User]
['constructor', 'greet']

Explanation

  1. typeof User:

    • In JavaScript, classes are syntactic sugar over constructor functions, so typeof User will return `"function".
  2. User.prototype:

    • Shows an object with properties constructor and greet. The constructor property references the User function itself.
  3. User.prototype.constructor:

    • Shows the User function, indicating that the constructor property points to the User function.
  4. Object.getOwnPropertyNames(User.prototype):

    • Returns an array of the property names directly found on User.prototype, which are constructor and greet.
github-actions[bot] commented 2 months ago

134 - Pull Request updated.