• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Understanding Constructor Functions

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
A constructor function is a special type of function used to create and initialize objects in programming, particularly in object-oriented languages like JavaScript. Think of it as a blueprint or factory for making many similar objects.

Real-World Analogy


Imagine you're managing a car manufacturing company. Every car you build shares the same structure—engine, wheels, color, and brand—but each one has its own values.

Instead of manually building each car from scratch, you use a car-making machine (constructor function). You input values like color, brand, and engine size, and the machine builds the car for you.

Basic Syntax in JavaScript


function Car(brand, color, engineSize) {
this.brand = brand;
this.color = color;
this.engineSize = engineSize;
}

This is the constructor function. To create a car:


let car1 = new Car("Toyota", "Red", "2.0L");
let car2 = new Car("Honda", "Blue", "1.8L");

console.log(car1.brand); // Toyota
console.log(car2.color); // Blue

Notice the use of the new keyword—it tells JavaScript to:


  1. Create a new object.


  2. Set the prototype.


  3. Bind this to the new object.


  4. Return the object.
Tips & Tricks


??1 Always Use Capital Letters for Constructor Names

By convention, constructor functions start with capital letters.


function Person(name, age) {
this.name = name;
this.age = age;
}

??2 Use Prototypes to Share Methods

Defining methods inside the constructor creates a new copy of the method for each object. Use prototypes instead:


Person.prototype.greet = function() {
console.log("Hello, my name is " + this.name);
};

Why? Saves memory. All objects share the same method definition.

??3 Avoid Arrow Functions for Methods Using this

Arrow functions don’t bind this to the object instance.

Wrong:


Person.prototype.greet = () => {
console.log("Hi " + this.name); // `this` won't work here
};

Correct:


Person.prototype.greet = function() {
console.log("Hi " + this.name);
};

??4 Constructor Validation

You can include checks inside the constructor to validate inputs.


function Product(name, price) {
if (!name || price < 0) {
throw new Error("Invalid product data.");
}
this.name = name;
this.price = price;
}
Practical Use Cases


??1 Creating Multiple Users in a Web App


function User(username, role) {
this.username = username;
this.role = role;
}


let admin = new User("solomon", "admin");
let guest = new User("visitor", "guest");

Useful for managing different user roles.

??2 Building a Task Manager App


function Task(title, deadline) {
this.title = title;
this.deadline = deadline;
this.completed = false;
}

Task.prototype.markComplete = function() {
this.completed = true;
};

let task1 = new Task("Submit assignment", "2025-05-15");
task1.markComplete();

??3 Inventory System for a Store


function Item(name, stock) {
this.name = name;
this.stock = stock;
}

Item.prototype.sell = function(quantity) {
if (this.stock >= quantity) {
this.stock -= quantity;
console.log(quantity + " sold!");
} else {
console.log("Not enough stock.");
}
};

let rice = new Item("Bag of Rice", 50);
rice.sell(10); // 10 sold!
Advanced Tip: Object.create() vs Constructor Functions


You can also create objects using Object.create() but constructor functions with new provide a cleaner structure when creating many similar objects.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу