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

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

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

? Advanced Objects in JavaScript: A Deep Dive

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
JavaScript objects are powerful and flexible, and once you're comfortable with the basics, it's time to explore some advanced object features that can make your code cleaner, more dynamic, and easier to maintain. In this article, we'll explore advanced concepts like:

  • Object Destructuring
  • Computed Property Names
  • Object Property Shorthand
  • Object Methods
  • The this keyword
  • Prototypes & Inheritance
  • Object.defineProperty
  • Object.freeze & Object.seal

Let’s dive into each of them with practical examples.

? 1. Object Destructuring


Destructuring lets you extract values from an object in a clean way.


const user = { name: "Alice", age: 25, country: "USA" };

const { name, age } = user;
console.log(name); // Alice
console.log(age); // 25

You can also rename variables:


const { country: location } = user;
console.log(location); // USA
? 2. Computed Property Names


Dynamic keys can be created using square brackets:


const key = "score";
const obj = {
[key]: 42
};

console.log(obj.score); // 42

Useful when building objects from variables.

✍ 3. Property Shorthand


When the variable name and key are the same, you can write:


const name = "John";
const age = 30;

const person = { name, age };
console.log(person); // { name: 'John', age: 30 }
?️ 4. Object Methods


You can define functions inside objects:


const calculator = {
add(a, b) {
return a + b;
},
};

console.log(calculator.add(2, 3)); // 5

Note the method shorthand: no need for function keyword.

? 5. The this Keyword


Inside object methods, this refers to the object itself:


const car = {
brand: "Toyota",
getBrand() {
return this.brand;
},
};

console.log(car.getBrand()); // Toyota

⚠ Be careful: arrow functions don’t have their own this.

? 6. Prototypes & Inheritance


JavaScript objects can inherit properties using prototypes:


const animal = {
speak() {
console.log("Animal speaks");
}
};

const dog = Object.create(animal);
dog.bark = function () {
console.log("Woof!");
};

dog.speak(); // Animal speaks
dog.bark(); // Woof!
?️ 7. Object.defineProperty()


Allows fine control over object properties:


const obj = {};
Object.defineProperty(obj, "secret", {
value: "Hidden",
writable: false,
enumerable: false
});

console.log(obj.secret); // Hidden
obj.secret = "Exposed";
console.log(obj.secret); // Still Hidden

Useful for creating read-only or hidden properties.

? 8. Object.freeze() and Object.seal()

  • Object.freeze(obj) → Makes the object completely immutable.
  • Object.seal(obj) → Allows changes to existing properties but disallows adding or deleting.

const config = {
apiKey: "123"
};

Object.freeze(config);
config.apiKey = "456"; // Won’t change
console.log(config.apiKey); // 123
? Conclusion


Advanced object features in JavaScript can help you write more concise, flexible, and scalable code. Whether you’re working on a small script or a large application, mastering these features can give you a major edge.

Keep experimenting with objects — they’re the backbone of JavaScript programming!


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

 
Вверх Снизу