我是JavaScript OO编程的新手,请耐心等待任何歧义。
我有一个方法需要一个对象作为其参数。 必需对象设置要使用的方法的选项。
var objInstance = csvObj.getData({
url: '', // csv url
format: '', // return data format
onComplete: function (output) {
// a function that will display data returned
}
});
csvObj定义如下
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 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
}
}());
}
};
问题:是否有更好的方法来处理对象参数,而不仅仅是像这样访问:
var privateProperty = object.property;
或
var privateMethod = object.method;
答案 0 :(得分:2)
您的方法完全有效。你也可以这样做:
var privateMethod = object['method'];
这对于动态获取属性非常方便,但通常我更喜欢object.method
,因为它更容易阅读。