JSFiddle - React, Tailwind, and code Playground
HTML
Open the console and play with the <code>getFreeChain</code> function!
<!-- Demo created by Rob Wu <[email protected]> for http://stackoverflow.com/q/17197430 -->
<!-- Included external library for self-contained example
<script src="https://es-lab.googlecode.com/svn/trunk/src/proxies/DirectProxies.js"></script> -->
<script>
// Copyright (C) 2011 Software Languages Lab, Vrije Universiteit Brussel
// This code is dual-licensed under both the Apache License and the MPL
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is a prototype implementation of Harmony Direct Proxies.
*
* The Initial Developer of the Original Code is
* Tom Van Cutsem, Vrije Universiteit Brussel.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
*/
// ****************************************************************************
// Deprecating Warning: DirectProxies.js is superseded by the...
JavaScript
function getFreeChain(object) {
var handler = {
get: function(target, name) {
if (name in target)
return target[name];
var newTarget = target[name] = {};
return new Proxy(newTarget, handler);
}
};
return new Proxy(object, handler);
}
window.onload = function() {
// Usage:
var obj = {};
var magicalObj = getFreeChain(obj);
magicalObj.a.b.c.d.e.g = 1;
console.log(magicalObj.a.b.c.d.e.g); // 1
console.log(obj.a.b.c.d.e.g); // 1
obj.x.y.z = 1; // TypeError: obj.x is undefined
};