, который доступен в объекте window
веб-браузеров. Объект Proxy
используется для создания прокси для другого объекта, что позволяет вам перехватывать и настраивать его поведение. Вот некоторые часто используемые методы объекта Proxy
с примерами кода:
-
get(target, свойство, получатель)
: перехватывает доступ к свойству прокси-объекта.const target = { name: 'John' }; const handler = { get: function(target, property, receiver) { console.log(`Getting property: ${property}`); return target[property]; } }; const proxy = new Proxy(target, handler); console.log(proxy.name); // Output: Getting property: name, John
-
set(цель, свойство, значение, получатель)
: перехватывает назначение свойства прокси-объекта.const target = { name: 'John' }; const handler = { set: function(target, property, value, receiver) { console.log(`Setting property: ${property} = ${value}`); target[property] = value; return true; } }; const proxy = new Proxy(target, handler); proxy.name = 'Jane'; // Output: Setting property: name = Jane console.log(proxy.name); // Output: Jane
-
apply(target, thisArg, аргументыList)
: перехватывает вызовы функций прокси-объекта.function sum(a, b) { return a + b; } const handler = { apply: function(target, thisArg, argumentsList) { console.log(`Calling function: sum(${argumentsList.join(', ')})`); return target.apply(thisArg, argumentsList); } }; const proxy = new Proxy(sum, handler); console.log(proxy(2, 3)); // Output: Calling function: sum(2, 3), 5
-
has(target, property)
: перехватывает операторin
, чтобы проверить, существует ли свойство в прокси-объекте.const target = { name: 'John' }; const handler = { has: function(target, property) { console.log(`Checking property existence: ${property}`); return property in target; } }; const proxy = new Proxy(target, handler); console.log('name' in proxy); // Output: Checking property existence: name, true
Это всего лишь несколько примеров методов, доступных в объекте Proxy
. Есть и другие методы, которые вы можете изучить в документации по JavaScript.