Skip to content

Instantly share code, notes, and snippets.

@andrijac
Created August 17, 2012 08:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrijac/3376877 to your computer and use it in GitHub Desktop.
Save andrijac/3376877 to your computer and use it in GitHub Desktop.
create property in javascript, cross browser, createProperty function
function createProperty(config) {
var options = { initValue: null, setter: null, getter: null },
_config = $.extend(options, config),
_value = _config.initValue,
context;
return function (value) {
if (value === undefined) {
if (_config.getter && typeof _config.getter === "function") {
context = { value: _value };
return config.getter(context);
}
return _value;
} else {
if (_config.setter && typeof _config.setter === "function") {
context = { value: _value };
_config.setter(context, value);
_value = context.value;
} else {
_value = value;
}
}
};
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/qunit/qunit-git.css" />
<title>createProperty test</title>
</head>
<body>
<div id="qunit"></div>
<!---------- scripts ----------------->
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script src="http://code.jquery.com/qunit/qunit-git.js"></script>
<script>
$(function () {
'use strict';
function createProperty(config) {
var options = { initValue: null, setter: null, getter: null },
_config = $.extend(options, config),
_value = _config.initValue,
context;
return function (value) {
if (value === undefined) {
if (_config.getter && typeof _config.getter === "function") {
context = { value: _value };
return config.getter(context);
}
return _value;
} else {
if (_config.setter && typeof _config.setter === "function") {
context = { value: _value };
_config.setter(context, value);
_value = context.value;
} else {
_value = value;
}
}
};
}
var Foo = {};
Foo.propX = createProperty({
initValue: 1,
setter: function (context, value) {
context.value = value + 1;
},
getter: function (context) {
return context.value;
}
});
Foo.propY = createProperty();
module("Test createProperty.");
test("Test propX", function () {
equal(Foo.propX(), 1, "initial propX value is OK.");
Foo.propX(22);
equal(Foo.propX(), 23, "propX value is OK.");
});
test("Test propY", function () {
equal(Foo.propY(), null, "initial propY value is OK.");
Foo.propY('test111');
equal(Foo.propY(), 'test111', "propY value is OK.");
});
});
</script>
</body>
</html>
@andrijac
Copy link
Author

need to add setter and getter in config too.

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