Class Constructors
When you create a new object from a class in JavaScript, you often want to set up its initial state—such as assigning values to its properties. This is where the constructor method comes in. The constructor is a special method inside a class definition that is automatically called when you use the new keyword to create an instance of the class. You can use it to set up the properties of the object with specific values, usually by passing arguments to the constructor when creating the object.
12345678910class Person { constructor(name, age) { this.name = name; this.age = age; } } const user = new Person("Alice", 30); console.log(user.name); // "Alice" console.log(user.age); // 30
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how the constructor method works in this example?
What happens if I don't define a constructor in my class?
How can I add more properties to the Person class?
Awesome!
Completion rate improved to 6.25
Class Constructors
Свайпніть щоб показати меню
When you create a new object from a class in JavaScript, you often want to set up its initial state—such as assigning values to its properties. This is where the constructor method comes in. The constructor is a special method inside a class definition that is automatically called when you use the new keyword to create an instance of the class. You can use it to set up the properties of the object with specific values, usually by passing arguments to the constructor when creating the object.
12345678910class Person { constructor(name, age) { this.name = name; this.age = age; } } const user = new Person("Alice", 30); console.log(user.name); // "Alice" console.log(user.age); // 30
Дякуємо за ваш відгук!