JavaScript set()

0
11KB

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.

Examples

 

Defining a setter on new objects in object initializers

The following example define a pseudo-property current of object language. When current is assigned a value, it updates log with that value:

const language = {
  set current(name) {
    this.log.push(name);
  },
  log: [],
};

language.current = "EN";
console.log(language.log); // ['EN']

language.current = "FA";
console.log(language.log); // ['EN', 'FA']

Note that current is not defined, and any attempts to access it will result in undefined.

Rechercher
Catégories
Lire la suite
Science Fiction and Fantasy
Batman Begins. (2005)
After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from...
Par Leonard Pokrovski 2023-02-03 16:09:37 0 23KB
Жизненные вопросы
Звёздочки на земле. Like Stars on Earth. (2007)
Маленький мальчик 8 лет Ишан Авасти с рождения немного отличается от других детей. Ему дается с...
Par Nikolai Pokryshkin 2023-02-01 22:21:15 0 32KB
Business
What Is the Cost of Living Like in Silicon Valley?
Silicon Valley, the global hub of technology and innovation, offers tremendous career...
Par Dacey Rankins 2025-04-28 16:26:57 0 11KB
Personal Finance
How to Get Out of Debt and Pay It Off Faster
How to Get Out of Debt and Pay It Off Faster Debt can feel overwhelming — whether...
Par Leonard Pokrovski 2025-10-29 18:40:04 0 4KB
Financial Services
Perfect competition and why it matters
Key points A perfectly competitive firm is a price taker, which means that it...
Par Mark Lorenzo 2023-04-25 19:18:12 0 14KB

BigMoney.VIP Powered by Hosting Pokrov