Skip to content
This repository has been archived by the owner on Dec 17, 2021. It is now read-only.

Latest commit

 

History

History
74 lines (51 loc) · 1.94 KB

has.md

File metadata and controls

74 lines (51 loc) · 1.94 KB

Observer.has()

This method is used to test property presence. It corresponds to the JavaScript's built-in Reflect.has() function, which is itself the programmatic alternative to the JavaScript in operator – property in obj.

Observer.has() brings the added benefit of triggering interceptors.

Syntax

// Test the presence of a property.
let exists = Observer.has(obj, propertyName);

Parameters

  • obj - an object or array.
  • propertyName - the property name to check.

Return Value

Boolean

Usage

let obj = {
    fruit:'orange',
    brand:'apple',
};

let exists = Observer.has(obj, 'fruit');

Usage as a Trap's "has" Handler

Observer.has() can be used as the "has" handler in Proxy traps.

let _obj = new Proxy(obj, {has: Observer.has});
let _arr = new Proxy(arr, {has: Observer.has});

Exists operations will now be forwarded to Observer.has() and interceptors that may be bound to the object will continue to respond.

let exists = 'fruit' in _obj;
let exists = '1' in _arr;

Intercepting Observer.has()

Using Observer.intercept(), it is possible to intercept calls to Observer.has(). When a "has" operation triggers an interceptor, the interceptor will receive an event object containing the property name to check.

Observer.intercept(obj, 'has', (event, recieved, next) => {
    // What we recieved...
    console.log(event.name);
    // The read operation
    return event.name in obj;
});

let exists = Observer.has(obj, 'fruit');

Related Methods