Search

12/28/2007

javascript access control: private variables

lixo.org :: JavaScript: Put everything in a namespace


var Article = Article ? Article : new Object();
Article.title = “Report: School Shootings Help Prepare Students For Being Shot In Real World”;
Article.save = function() {
alert(”Saving ” + this.title);
}

use the object literal notation directly:


var Article = Article ? Article : {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”,
save: function() {
alert(”Saving ” + this.title)
}
}

These two last examples are great if you’re not that concerned about exposing the ‘title’ attribute to the rest of the world. If there is a chance that problems could arise if some other piece of code changed it directly, there is a solution:

var Article = Article ? Article : function() {
var private = {
title: “Report: School Shootings Help Prepare Students For Being Shot In Real World”
};

var public = {
getTitle: function() {
return private.title;
},

save: function() {
alert(”Saving ” + this.getTitle());
}
}

return public;
}();

by creating an anonymous function that returns the object I want to define, and then immediately calling it (note the ‘()’ at the last line), I can hide whatever I don’t want other parts of the code to see - it’s all tucked away in the local context of that anonymous function.

沒有留言: