Home > Web Front-end > JS Tutorial > body text

The Power of Proxy

WBOY
Release: 2024-09-05 22:34:33
Original
426 people have browsed it

The Power of Proxy

Proxy object is one of the most powerful yet underused features in JavaScript!

It allows you complete control over how your objects behave in JavaScript by defining custom behavior for basic operations on objects, like getting or setting properties.

It can also be used to create custom validation, data binding, logging, or even create fully reactive objects—without needing a library!

Here’s a simple example:

const user = {
  name: 'Zain',
  age: 22
};

const handler = {
  get: (target, prop) => {
    console.log(`Getting property ${prop}`);
    return prop in target ? target[prop] : 'Property does not exist';
  },
  set: (target, prop, value) => {
    if (prop === 'age' && typeof value !== 'number') {
      console.log('Invalid age type. It should be a number.');
    } else {
      console.log(`Setting property ${prop} to ${value}`);
      target[prop] = value;
    }
    return true;
  }
};

const proxiedUser = new Proxy(user, handler);

console.log(proxiedUser.name); // Logs: Getting property name
proxiedUser.age = 'twenty-two'; // Logs: Invalid age type. It should be a number.
proxiedUser.age = 23; // Logs: Setting property age to 23

Copy after login

With Proxy, you can intercept and redefine almost any fundamental behavior for objects—adding a layer of control and customization that's unmatched by any other feature in JavaScript!


To stay updated with more content related to web development and AI, feel free to follow me. Let's learn and grow together!

The above is the detailed content of The Power of Proxy. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!