<ol>
<li>Click "get" then "set" to see the value update.</li>
<li>Click "get" again to verify value updated.</li>
</ol>
<pre class="output">No output yet.</pre>
<button class="get">Get Foo</button>
<button class="set">Set Foo to 10</button>
// Internal reference
_foo = 0;
// Helpers
function hasArguments(args) {
return args.length > 0;
}
function updateOutput(val) {
$('.output').html(val);
}
// Getter setters
function setFoo(val) {
_foo = val;
// over simplified example, but sometimes
// its useful to return success from a setter.
var success = true;
return success;
}
function getFoo(val) {
return _foo;
}
// Sugar method
function foo(val) {
// hasArguments enables a simple ternary to run the getter or setter.
// method returns value from get or set
// obviously we're most interested in the get return value
// but a return value from the setter can be useful too!
return hasArguments(arguments) ? setFoo(val) : getFoo(val)
}
// Ui handlers
$('.set').on('click', function (e) {
success = foo(10);
if (success) {
updateOutput('set foo to 10! foo now = ' + foo());
}
});
$('.get').on('click', function (e) {
updateOutput("fetched foo's value of " + foo());
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.