Home > Article > Web Front-end > Understanding the use of JavaScript Proxy() objects (code examples)
Proxy objects in JavaScript are used to define custom behaviors for basic operations (e.g., property lookups, assignments, enumerations, function calls, etc.).
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: 'John Nash', Age: 25 }; const handler = { // target表示Person,而prop表示代理属性。 get: function(target, prop) { if (prop === 'FirstName') { return target.Name.split(' ')[0]; } if (prop === 'LastName') { return target.Name.split(' ').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!