Introduction

As the founder and writer of Euphor.ca, my journey into wellness, psychedelics, and personal growth has been transformative. I created this lifestyle magazine to share valuable insights, knowledge…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Proxy in javascript

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for the object.

get method can redefine the access of an atrribute, it accepts three params(target object, atrribute name and proxy instantiation).

get method can be inherited.

In above code, interception operation is defined on Prototype object, so this interception will be triggered when accessing the inherited attribute ofobj .

set method can intercept an attribute’s assignment operation. It can accepts four arguments (target object, property name, property value, Proxy instantiation).

In above code, any value that does not meet the requirements will trigger an error.

Sometimes, we want to add inner properties with a underscore in an object, which means we don’t want these properties to be used outside. We can take advantage of get and set to achieve this.

In strict mode, set must return turn , or it will cause error.

apply method can intercept invocation, call and apply operation.

apply accepts three arguments (target object, context of the target object(this), argument array of target object).

Example

In above code, p is the instantiation of Proxy. When p is called p() , it will be intercepted by apply method and returns a string.

Another example

Proxy object can intercept any property, so it can be used to implement web server.

Above code creates a web server interface returning different kinds of data. Proxy can intercept any property, so we don’t need to write matching method for every data, just one Proxy is enough.

And Proxy can be used to implement ORM layer for database.

Add a comment

Related posts:

Test Cases With Django

To check what ever you write in your application development is it true Or it functioning as per your expectation. when your project is large and large then how you handle correctness of your…

Evicting a Tenant in Texas

Evictions in Texas are governed by Chapter 24 of the Texas Property Code. There are three steps to evicting a tenant that is in breach of the lease or holding over beyond the term of the lease…

How I Bought My First Rental Property

There I was receiving my first paycheque as a full-time designer. For a 21-year-old, receiving a cheque for $945.13, it was a lot of money. More money than my account has ever seen. I thought I was…