Metaprogramming experiments: Selector Properties

Hello everyone!

A few days ago I wrote a post about “Virtual Instances in JavaScript with Proxy API – JSDataViews“.
It’s an approach on how to calculate the data representation of a variable at runtime with the help of the new Proxy API.

Today I want to show another feature which is part of the core of JSDataViews

Selector Properties

A lot of people are familiar with jQuery. The development of jQuery is driven by the fact that the DOM is a hierarchical, complex data structure and people need an easy way to access and manipulate different parts of it.
Since JavaScript objects can reach a similar complexity I was looking for an easy and nice way to run similar queries on them.

The new Proxy API allows developers to extend the natural behaviour of JavaScript objects in a meta-programming way.
You can find some really interesting slides from Brendan Eich about the Proxy API, meta-programming and the new opportunities for developers on Slideshare.

In my experiments I came up with an idea on extending the normal property access to the effect, that the nested character of an object is considered as well – I call this kind of property “Selector Properties”.


The following examples are taken from the test cases of JSDataViews.

Example #1 – query by key:value

This selector queries first order childs and returns those conatining a property named “status” with value “is working”.

Example #2 – query by predicate

This selector is searching for first order childs containing a property “age” that passes the given predicate.
At the moment of writing the following operators are supported:

Example #3 – recursive queries

This selector searches within the whole object structure for any nested object that contains a property “age” that passes the predicate.
For this reason, not only “john doe” but also his friend “alex” and the dog of max are returned since they are all under 25 as well.
The >> operator indicates that we want to run this query recursive.

Example #4 – “Chaining” and implicit setters

With JSDataViews one can also combine queries with setters in the following way:

The changes are executed on every instance in the returned set of objects.

Please note

The demonstrated functionality is layered on the JavaScript language and is not part of it.
The examples are very experimental and should not be used in production code.
It is really dangerous to do stuff like this since the borders of your semantics and the intended usage of Javascript objects are blurred. For this reason the resulting code can become confusing.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.