Перейти к основному содержимому
Frontend — это бесплатный бонус CodeMentor AI; основной продукт — Python. Зарегистрируйся, чтобы сохранить прогресс и открыть все 299 уроков фронтенда + 1,100+ уроков Python.Зарегистрироваться — бесплатно
← ⚡ JavaScript & the browser·Модуль C1 · Урок 6
ЗаданиеDeclare const user = { name: 'Anna', age: 30 }. Destructure name and age into local consts. Build const greeting = \`hi, \${name} (\${age})\`. Log greeting.

Объекты: свойства, методы, деструктуризация

75 XP7 minFREE
Теория

Objects in 30 seconds

const user = {
  name: "Anna",
  age: 30,
  greet() { return `hi, ${this.name}`; },
};

user.name;           // "Anna"
user["age"];         // 30 (bracket access works too)
user.greet();        // "hi, Anna"

Properties hold values. Methods are properties whose value is a function. this inside a method refers to the object the method was called on.

Destructuring — pull values out by name

const { name, age } = user;
console.log(name, age);       // "Anna" 30

Reads as: "from user, give me name and age as local variables." Works the same in function parameters:

function welcome({ name }) {
  return `hi, ${name}`;
}
welcome(user);                // "hi, Anna"

You'll see this every day in React (props) and in any modern API client (response objects).

Rename + default in one go

const { name: displayName, role = "guest" } = user;

Pulls user.name into a local called displayName, and provides "guest" if user.role is missing. Pure ergonomics, very common in component code.

Spread to merge

const updated = { ...user, age: 31 };

New object with every key from user, then age overridden to 31. The original user is untouched. This is the immutable-update pattern React/Redux/etc rely on.

2 вкладок
Живой просмотр
console output appears here…
← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.