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

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

藏色散人
藏色散人Original
2019-03-27 15:19:512595browse

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);

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>

Output:

[object Object]
John
Nash

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!

Statement:
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