Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active March 8, 2018 11:45
Show Gist options
  • Save yckart/6404585 to your computer and use it in GitHub Desktop.
Save yckart/6404585 to your computer and use it in GitHub Desktop.
getSet

This is an really simple implementation of getters and setters. And inspired by https://github.com/allouis/prototypes/tree/master/getSet.

Just overwrite your function-prototype with the getSet-function call.

function Test() {}
Test.prototype = getSet();

You can pass in an optional object to use as the key/value store:

function Test() {}
Test.prototype = getSet(Test.prototype);

To add new properties to the object use get('key') and set('key', 'value') / set({key: 'value'}):

function Test() {}
Test.prototype = getSet();

var test = new Test();
test.set('foo', 'bar');
test.set({
  foz: 'baz'
});

test.get('foo') // => 'bar'
test.get('foz') // => 'baz'
function (
a, // our cache-object (optional)
b // undefined-placeholder
) {
a = a || {}; // if cache-object is not given, use an object
return {
set: function (c, d) {
if (d !== b) return a[c] = d; // value is defined, so assign it to the attributes-cache
// value is null/undefined, so key must be an object
for (d in c) // iterate over it
a[d] = c[d] // assign its values to our cache
},
get: function (c) {
return a[c] // return the value depending on given property
}
}
}
function(a,b){a=a||{};return{set:function(c,d){if(d!=b)return a[c]=d;for(d in c)a[d]=c[d]},get:function(c){return a[c]}}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "getSet",
"description": "Defines two methods 'get' and 'set'. They make it easier to get/set properties on objects.",
"keywords": [
"get",
"set",
"getter",
"setter",
"object"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>undefined</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
function Test() {}
Test.prototype = getSet();
var test = new Test();
test.set('name', 'test');
test.set({
type: 'object',
constructor: 'Test'
});
var ret = document.getElementById('ret');
ret.innerHTML += test.get('name') + ', ';
ret.innerHTML += test.get('constructor') + ', ';
ret.innerHTML += test.get('type');
</script>
@atk
Copy link

atk commented Sep 2, 2013

This will not store false or null inside the cache, you need to use !== to be typesafe.

@yckart
Copy link
Author

yckart commented Sep 3, 2013

@atk Whoop's was a typo. Fixed it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment