>  기사  >  웹 프론트엔드  >  JavaScript의 프록시에 대한 자세한 소개(코드 예)

JavaScript의 프록시에 대한 자세한 소개(코드 예)

不言
不言앞으로
2018-12-10 17:52:199160검색

이 글은 JavaScript의 Proxy에 대한 자세한 소개(코드 예제)를 제공합니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

Proxy를 사용하면 모든 개체의 대부분의 동작을 모니터링하고 방해할 수 있으며 보다 맞춤화된 프로그램 동작을 달성할 수 있습니다.

사용법: 새 프록시(대상, 처리기).

Proxy는 동작 수신 방법을 설정하여 해당 객체에 대한 프로그램의 동작을 캡처합니다.

    const obj = {};
    const proxy = new Proxy(obj, {
        // ...
    })

프록시의 생성자는 두 개의 매개변수를 허용합니다. 첫 번째 매개변수는 패키징해야 하는 대상 객체입니다. 두 번째 매개변수는 대상 객체의 동작을 모니터링하는 데 사용되는 리스너입니다. 해당 프로그램 동작을 모니터링하는 일부 매개변수.
청취 속성, 매개변수 및 콘텐츠 모니터링

#🎜 🎜 # 듣는 콘텐츠has(대상, 소품) 사용 명령문 듣기 get(target, prop, receive)Listen to the property of the 대상 객체 읽기set(target, prop, value, receive)속성 할당 듣기 대상 객체의 deleteProperty(target, prop)Delete 문의 삭제 속성 동작 듣기 대상 객체에서#🎜 🎜#ownKeys#🎜🎜 #apply(target, thisArg, 인수)대상 함수의 호출 동작 듣기( 대상 개체로) (target, 인수, newTarget)(target)# 🎜🎜#setPrototypeOf(대상, 프로토타입)읽기 듣기 Objext.setPrototypeOf()# 🎜🎜#Objext 읽기 듣기 .isExtensible()#🎜 🎜#preventExtensions(target)Objext.preventExtensions() 읽기를 들어보세요. getOwnPropertyDescriptor# 🎜 🎜#definePropertyhas
const p = new Proxy({}, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return true;
    }
})

console.log('foo' in p);
// Checking "foo" is in the target or not
// true
const obj = {foo: 1};

Object.preventExtensions(obj);

const p = new Proxy(obj, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return false; 
    }
})

console.log('foo' in p);   
//抛出Uncaught TypeError:
2. 확인 중인 속성 키가 대상 개체에 존재하고 해당 속성의 구성 가능한 구성이 false인 경우 청취 메서드는 false를 반환할 수 없습니다.
const obj = {};

Object.defineProperty(obj, 'foo', {
    configurable: false,
    value: 10
})

const p = new Proxy(obj, {
    has(target, prop){
        console.log(`Checking "${prop}" is in the target or not`);
        return false;
    }
})

console.log('foo' in p);
//抛出Uncaught TypeError:
속성 값 청취자 매개변수
(target) Object.getOwnPropertyName() 읽기를 듣습니다.
#🎜 🎜# construct
다음 동작 듣기 인스턴스를 생성하기 위해 new를 사용하는 대상 생성자(대상 객체) getPrototypeOf
Objext.getPrototypeOf()
isExtensible (target)
(target, prop) Objext.getOwnPropertyDescriptor() 호출 듣기# 🎜 🎜#
#🎜 🎜#(target, property, descriptor) Object.defineProperty()에 대한 호출 듣기#🎜🎜 #
프록시 처리기가 문자열 또는 숫자인지 확인하는 프로그램 프로세스를 모니터링하기 위해 수신 대기 방법을 정의할 수 있습니다. in 문을 통해 Proxy의 대상 객체에 있는 특정 속성의 속성 키입니다. 이 청취 방법에 대해 주의해야 할 두 가지 상황이 발생하면 TypeError가 발생합니다. 1. Object.preventExtensions()를 통해 다른 프로그램에 의해 대상 객체가 비활성화된 경우(객체는 새 속성을 추가할 수 없으며 읽기, 작업 및 삭제를 포함하여 현재 존재하는 속성에서만 작동할 수 있습니다. 그러나 일단 삭제되면 다시 정의할 수 없습니다) 함수이고 확인 중인 속성 키가 대상 객체에 존재하는 경우 청취 메서드는 false를 반환할 수 없습니다.
get

Getter는 알려진 속성 키만 모니터링할 수 있지만 모든 속성 읽기 동작을 가로챌 수는 없지만 프록시는 가져오기 수신 방법을 설정하고 모든 속성 읽기를 가로채고 방해할 수 있습니다. 대상 객체의 행동.

const obj = {foo: 1};
const p = new Proxy(obj, {
    get(target, prop){
        console.log(`Program is trying to fetch the property "${prop}".`);
        return target[prop];
    }
})

alert(p.foo);  // Program is trying to fetch the property "foo".
alert(p.something);    // Program is trying to fetch the property "something".
 이 청취 방법에도 주의할 점이 있습니다. 대상 객체의 읽기 속성 중 구성 가능 및 쓰기 가능 속성이 모두 false인 경우 청취 방법에서 반환되는 값은 원본과 동일해야 합니다. 대상 개체의 속성이 일치합니다.

const obj = {};

Object.defineProperty(obj, 'foo', {
    configurable: false,
    value: 10,
    writable: false
})

const p = new Proxy(obj, {
    get(target, prop){
        return 20;
    }
})

console.log(p.foo);
set

—handler.set는 대상 객체의 모든 속성 할당 동작을 모니터링하는 데 사용됩니다. 대상 객체 자체의 속성이 쓰기 가능하지 않거나 구성 가능하지 않은 경우 set은 이 속성의 값을 변경해서는 안 되며 동일한 값만 반환할 수 있습니다. 그렇지 않으면 오류가 보고됩니다.

const obj = {};
const p = new Proxy(obj, {
    set(target, prop, value){
        console.log(`Setting value "${value}" on the key "${prop}" in the target object`);
        target[prop] = value;
        return true;
    }
})

p.foo = 1;  
// Setting value "1" on the key "foo" in the target object
apply

handler.apply , 프록시는 호출 동작을 모니터링하기 위한 속성이 있는 대상 개체로서의 함수도 제공합니다.

const sum = function(...args) {
  return args
    .map(Number)
    .filter(Boolean)
    .reduce((a, b) => a + b);

}

const p = new Proxy(sum, {
  apply(target, thisArg, args) {
    console.log(`Function is being called with arguments [${args.join()}] and context ${thisArg}`);
    return target.call(thisArg, ...args);
  }
})

console.log(p(1, 2, 3));
// Function is being called with arguments [1,2,3] and context undefined
// 6
construct

- handler.construct, 프록시는 클래스를 대상 수신 개체로 사용하고 새 문을 통해 새 인스턴스를 생성하는 동작을 모니터링할 수도 있습니다. 생성자 함수에서 생성자로 다시 사용됩니다.

class Foo{};

const p = new Proxy(Foo, {
    construct(target, args, newTarget){
        return {arguments: args}    // 这里返回的结果会是 new 所得到的实例
    }
});

const obj = new p(1, 2, 3);
console.log(obj.arguments);  // [1, 2, 3]

취소 가능한 프록시 개체 만들기

사용법: Proxy.revocable(대상, 처리기): (프록시, 취소).

const obj = {foo: 10};
const revocable = Proxy.revocable(obj, {
    get(target, prop){
        return 20;
    }
})
const proxy = revocable.proxy;
console.log(proxy.foo); // 20
revocable.revoke();
console.log(proxy.foo); 
// TypeError: Cannot perform 'get' on a proxy that has been revoked

Proxy.revocable(target, handler)는 두 가지 속성을 가진 객체를 반환합니다. 프록시 중 하나는 함수에 의해 생성된 취소 가능한 프록시 객체이고, 다른 하나는 다음에 의해 생성된 취소 가능한 프록시 객체입니다. 함수. 방금 Proxy 객체의 취소 방법입니다.

위 내용은 JavaScript의 프록시에 대한 자세한 소개(코드 예)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제