I’ve trying to create a javascript object with public methods and public variables:
jeeni.DataGrid = (function(elementId){
var divId = elementId;
var div;
var saveUrl;
var columns;
var dataUrl;
var validate = function(){
console.log("divId: " + (divId));
console.log("div: " + div);
console.log("saveUrl: " + saveUrl);
console.log("columns: " + columns);
console.log("dataUrl: " + dataUrl);
};
return {
toString:validate,
dateURL:dataUrl,
saveURL:saveUrl,
columnDefs:columns
};
});
and I use it like this:
<script>
$(document).ready(function() {
var grid = new jeeni.DataGrid("myDataGrid");
grid.saveURL = "http://www.jeeni.co.uk/grid/save";
grid.dataURL = "http://www.jeeni.co.uk/grid/data";
grid.columnDefs = "[{text:'Column1',width:75}, {text:'Column2',width:150}]";
grid.toString();
});
</script>
But at the console I get:
divId: myDataGrid
div: undefined
saveUrl: undefined
columns: undefined
dataUrl: undefined
Can anyone explain why the undefined variables are undefined. Doesn’t the return make them public? And how do I get them to be assignable without having to use getters and setters.
Thanks
You’re currently taking the private variables, extracting the VALUES, and returning those in an object. The object you’re returning has no REFERENCE to the private variables, it merely has a copy. When you reassign a value after calling your function, you’re only changing the copy, not the private variable.
What you need to do is store your data directly on an object as all properties on an object are retrieved via REFERENCE. Example: