I am new to JavaScript OO programming please bear with me for any ambiguities.
I have a method that requires an object as its arguments. The required object sets options for the method to work with.
var objInstance = csvObj.getData({
url: '', // csv url
format: '', // return data format
onComplete: function (output) {
// a function that will display data returned
}
});
csvObj is defined below
var csvObj = {
getData: function (o) {
var format = o.format || 'json', //optional options
url = o.url, callback = o.onComplete; // required options
function include_js(jsurl) { // private function for performing cross dormain requests
var script = document.createElement("script");
script.type = "text/javascript";
script.src = jsurl;
document.getElementsByTagName("head")[0].appendChild(script);
}
(function () { // anonymous function for proccessing and returning data
if (typeof callback === 'function' && url) { // if require options are defined
if (!window.call_back) { // and global call_back function is not yet defined
window.call_back = callback; // define global call_back function (will be called when external script开发者_C百科 is loaded)
}
var restQuery = 'http://query.yahooapis.com/v1/public/yql?q=',
query = 'select * from csv where url="' + url + '" and columns="' + cols + '"',
yqlQuery = restQuery + encodeURIComponent(query) + '&format=' + data + '&callback=call_back'; // create YQL query
include_js(yqlQuery); // create a cross dormain YQL request
}
else {
alert('onComplete function or csv url not defined.'); // required options not defined
}
}());
}
};
Question: Is there a better way of handling object arguments than simply accessing like this:
var privateProperty = object.property;
or
var privateMethod = object.method;
Your approach is totally valid. You could do it like this, too:
var privateMethod = object['method'];
This can be very handy for dynamically getting properties, but in general i prefer object.method
, because it is much easier to read.
精彩评论