Home > Web Front-end > JS Tutorial > Understanding the use of JavaScript Proxy() objects (code examples)

Understanding the use of JavaScript Proxy() objects (code examples)

藏色散人
Release: 2019-03-27 15:19:51
Original
2619 people have browsed it

Proxy objects in JavaScript are used to define custom behaviors for basic operations (e.g., property lookups, assignments, enumerations, function calls, etc.).

Understanding the use of JavaScript Proxy() objects (code examples)

Syntax:

var p = new Proxy(target, handler);
Copy after login

Parameters: The proxy object accepts two parameters as described above, as follows:

target: The target object to be wrapped using Proxy (can be any type of object, including a function, class, or even another proxy).

handler: An object whose properties are functions that define the behavior of the agent when operations are performed on it.

Example:

<script> 
const Person = { 
    Name: &#39;John Nash&#39;, 
    Age: 25 
}; 
  
const handler = { 
    // target表示Person,而prop表示代理属性。
    get: function(target, prop) { 
        if (prop === &#39;FirstName&#39;) { 
            return target.Name.split(&#39; &#39;)[0]; 
        } 
        if (prop === &#39;LastName&#39;) { 
            return target.Name.split(&#39; &#39;).pop(); 
        } 
        else { 
            return Reflect.get(target,prop); 
        } 
    } 
}; 
  
const proxy1 = new Proxy(Person, handler); 
  
document.write(proxy1 + "<br>"); 
  
// 虽然没有像FirstName和LastName那样的属性,但是我们仍然获取到它们,就好像它们是属性而不是函数一样。
document.write(proxy1.FirstName + "<br>"); 
document.write(proxy1.LastName  + "<br>");      
</script>
Copy after login

Output:

[object Object]
John
Nash
Copy after login

Note: If NodeJs is installed, the above code can be run directly in the terminal, otherwise it can be run in an HTML file , by pasting the above code in a script tag and checking the output in the console of any web browser.

Related recommendations: "JavaScript Tutorial"

The above is the detailed content of Understanding the use of JavaScript Proxy() objects (code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template