Telegram Group & Telegram Channel
🖥 Функция-конструктор в JavaScript

Она позволяет задавать шаблон для объектов, чтобы каждый новый объект, созданный через этот конструктор, имел определенные свойства и методы. Давайте разберем, как работает функция-конструктор.

✏️ Создание функции-конструктора
Функция-конструктор выглядит как обычная функция, но она пишется с заглавной буквы по соглашению, чтобы отличаться от других функций. Внутри конструктора используется this для задания свойств создаваемого объекта.


function Person(name, age) {
this.name = name; // свойство name
this.age = age; // свойство age
}


🎮 Создание объектов с помощью конструктора
Чтобы создать объект с помощью конструктора, используется оператор new. Он:

- Создает новый пустой объект.
- Связывает его с this внутри конструктора.
- Возвращает этот объект.


const person1 = new Person("Alice", 25);
console.log(person1.name); // Alice
console.log(person1.age); // 25


Добавление методов в конструктор
Если мы добавим метод прямо в конструктор, то он будет копироваться в каждый новый объект, что может тратить память.


function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(`Hi, I'm ${this.name}`);
};
}

const person1 = new Person("Alice", 25);
person1.sayHello(); // Hi, I'm Alice


⚙️ Оптимизация с prototype
Для методов можно использовать prototype, чтобы метод существовал в одном экземпляре и не копировался для каждого объекта.


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

Person.prototype.sayHello = function() {
console.log(`Hi, I'm ${this.name}`);
};

const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);

person1.sayHello(); // Hi, I'm Alice
person2.sayHello(); // Hi, I'm Bob


💭 Как работает this в конструкторе
В функции-конструкторе this указывает на новый объект, который создается при вызове через new. Это позволяет настраивать свойства и методы нового объекта.

💎 Продвинутые аспекты
- Наследование. Используя прототипы, можно создавать наследуемые свойства и методы.
- Проверка с instanceof. Для проверки, создан ли объект через конструктор, можно использовать instanceof.


console.log(person1 instanceof Person); // true


#javascript #this #function
Please open Telegram to view this post
VIEW IN TELEGRAM



group-telegram.com/reactify_IT/1329
Create:
Last Update:

🖥 Функция-конструктор в JavaScript

Она позволяет задавать шаблон для объектов, чтобы каждый новый объект, созданный через этот конструктор, имел определенные свойства и методы. Давайте разберем, как работает функция-конструктор.

✏️ Создание функции-конструктора
Функция-конструктор выглядит как обычная функция, но она пишется с заглавной буквы по соглашению, чтобы отличаться от других функций. Внутри конструктора используется this для задания свойств создаваемого объекта.


function Person(name, age) {
this.name = name; // свойство name
this.age = age; // свойство age
}


🎮 Создание объектов с помощью конструктора
Чтобы создать объект с помощью конструктора, используется оператор new. Он:

- Создает новый пустой объект.
- Связывает его с this внутри конструктора.
- Возвращает этот объект.


const person1 = new Person("Alice", 25);
console.log(person1.name); // Alice
console.log(person1.age); // 25


Добавление методов в конструктор
Если мы добавим метод прямо в конструктор, то он будет копироваться в каждый новый объект, что может тратить память.


function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(`Hi, I'm ${this.name}`);
};
}

const person1 = new Person("Alice", 25);
person1.sayHello(); // Hi, I'm Alice


⚙️ Оптимизация с prototype
Для методов можно использовать prototype, чтобы метод существовал в одном экземпляре и не копировался для каждого объекта.


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

Person.prototype.sayHello = function() {
console.log(`Hi, I'm ${this.name}`);
};

const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);

person1.sayHello(); // Hi, I'm Alice
person2.sayHello(); // Hi, I'm Bob


💭 Как работает this в конструкторе
В функции-конструкторе this указывает на новый объект, который создается при вызове через new. Это позволяет настраивать свойства и методы нового объекта.

💎 Продвинутые аспекты
- Наследование. Используя прототипы, можно создавать наследуемые свойства и методы.
- Проверка с instanceof. Для проверки, создан ли объект через конструктор, можно использовать instanceof.


console.log(person1 instanceof Person); // true


#javascript #this #function

BY Reactify | Frontend Разработка


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/reactify_IT/1329

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

But the Ukraine Crisis Media Center's Tsekhanovska points out that communications are often down in zones most affected by the war, making this sort of cross-referencing a luxury many cannot afford. Unlike Silicon Valley giants such as Facebook and Twitter, which run very public anti-disinformation programs, Brooking said: "Telegram is famously lax or absent in its content moderation policy." Since January 2022, the SC has received a total of 47 complaints and enquiries on illegal investment schemes promoted through Telegram. These fraudulent schemes offer non-existent investment opportunities, promising very attractive and risk-free returns within a short span of time. They commonly offer unrealistic returns of as high as 1,000% within 24 hours or even within a few hours. During the operations, Sebi officials seized various records and documents, including 34 mobile phones, six laptops, four desktops, four tablets, two hard drive disks and one pen drive from the custody of these persons. Right now the digital security needs of Russians and Ukrainians are very different, and they lead to very different caveats about how to mitigate the risks associated with using Telegram. For Ukrainians in Ukraine, whose physical safety is at risk because they are in a war zone, digital security is probably not their highest priority. They may value access to news and communication with their loved ones over making sure that all of their communications are encrypted in such a manner that they are indecipherable to Telegram, its employees, or governments with court orders.
from jp


Telegram Reactify | Frontend Разработка
FROM American