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.
// 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
let obj = {
fruit:'orange',
brand:'apple',
};
let exists = Observer.has(obj, 'fruit');
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;
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');