Private Members in JavaScript
<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}
function Container(param) {
function dec() {
// private function
if (secret > 0) {
// encloures
secret -= 1;
return true;
} else {
return false;
}
}
this.member = param;
var secret = 3; // private variables only be made in constructor function
var that = this;
this.service = function () {
// privileged function
if (dec()) {
//return that.member;
return this.member;
} else {
return null;
}
};
}
var myContainer = new Container('abc');
doc(myContainer.service()); // abc
doc(myContainer.service()); // abc
doc(myContainer.service()); // abc
doc(myContainer.service()); // null
</script>
No comments :
Post a Comment