Skip to content

Instantly share code, notes, and snippets.

@kgryte
Created December 24, 2015 03:48
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgryte/713ab40f36c128bc1d52 to your computer and use it in GitHub Desktop.
Save kgryte/713ab40f36c128bc1d52 to your computer and use it in GitHub Desktop.
Using ES6 proxy with arrays.
/* jshint esnext:true */
function get( target, prop, receiver ) {
console.log( 'target: ' + target );
console.log( 'property: ' + prop );
// console.log( 'Receiver: ' + receiver );
return Reflect.get( target, prop, receiver );
}
var handler = {
'get': get
};
// Create a proxy for a plain array:
var proxy = new Proxy( [1,2,3,4,5], handler );
console.log( 'Result => beep: ' + proxy.beep );
console.log( 'Result => -123: ' + proxy[ -123] );
console.log( proxy.fill( 1 ) );
console.log( 'Result => 0: ' + proxy[ 0 ] );
// Set the prototype of a plain array to the proxy, based on the premise that the prototype of an array is an array...
var arr1 = [ 10, 20, 30, 40, 50 ];
Object.setPrototypeOf( arr1, proxy );
console.log( 'Result => beep: ' + arr1.beep );
console.log( 'Result => -123: ' + arr1[ -123 ] );
console.log( arr1.fill( 100 ) );
console.log( 'Result => 0: ' + arr1[ 0 ] );
// // Subclass a proxy...
// function ArrayProxy() {}
// ArrayProxy.prototype = proxy;
// class Arr extends ArrayProxy {
// constructor( x ) {
// super( x );
// }
// }
// var arr2 = new Arr();
// console.log( arr2.beep );
// console.log( arr2[ -123] );
// console.log( arr2.fill( 99 ) );
// console.log( arr2[ 0 ] );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment