我不确定如何在JS中实现OOP概念。
我有一个完全在其构造函数中声明的类:
function AjaxList(settings)
{
// all these vars are of dubious necessity... could probably just use `settings` directly
var _jq_choice_selector = settings['choice_selector'];
var _jq_chosen_list = settings['chosen_list'];
var _cb_onRefresh = settings['on_refresh'];
var _url_all_choices = settings['url_choices'];
var _url_chosen = settings['url_chosen'];
var _url_delete_format = settings['url_delete_format'];
var jq_choice_selector_form = _jq_choice_selector.closest("form");
if (DEBUG && jq_choice_selector_form.length != 1)
{
throw("There was an error selecting the form for the choice selector.");
}
function refresh()
{
_updateChoicesSelector();
_updateChosenList();
_cb_onRefresh();
};
AjaxList.prototype.refresh = refresh; // will this be called on all AjaxLists, or just the instance used to call it?
// AjaxList.refresh = refresh; // will this be called on all AjaxLists, or just the instance used to call it?
// ...
}
有多个AjaxList实例。当我在其中一个上调用
refresh()
时,我只希望其中一个列表刷新自身。在以下情况下:term_list = AjaxList(settings);
term_list.refresh();
refresh()
调用似乎使所有AjaxList刷新。正确的方法是什么?我正在使用jQuery,如果有什么不同的话。
最佳答案
您不应在构造函数中重新定义原型(prototype)函数。
如果要创建特权函数,请使用构造函数中的this.methodname =...。
function AjaxList() {
var privateVar = 0;
function privateFunction() {
//...
}
//create a refresh function just for this instance of the AjaxList
this.refresh = function() {
//privileged function, it can access the 'privateVar & privateFunction'
privateVar++;
}
}
//public functions that don't need access to the private variables/functions
AjaxList.prototype.publicFunction=function() {
};
另外,如果要创建适当的对象,则需要更改
term_list = AjaxList(settings);
至
term_list = new AjaxList(settings);