我认为问我问题的最好方法是举个例子。在 Javascript 中,想象以下场景:
function Tab(options) {
this.options = options;
}
Tab.prototype.doSomething = function () {
if(...){
//change tab1's options
//tab1.disabled = true
}else{
//change tab2's options
//tab2.disabled = true
}
//call a method on of mySlider instance (NOT myOtherSlider instance)
//mySlider.helloWorld();
}
//slider class
function Slider(options) {
....
}
Slider.prototype.helloWorld = function () {
...
//Access tab1's properties
//tab1.disabled should be "TRUE" since it was changed previously
//Access tab2's properties
...
}
function Accordion() {
this.name = 'accordion';
var tab1 = new Tab({disabled: true}),
tab2 = new Tab({disabled: false),
mySlider = new Slider({color: red}),
myOtherSlider = new Slider({color: blue});
}
几乎我希望所有类都知道在他们自己的类以及其他类中实例化的对象。
重要的部分是使实例同步。例如,对 tab1 属性的更改应该应用于/可见到访问 tab1 的任何其他对象。
我设法通过使用对象管理器类来回答我自己的问题
function ObjectManager (){
}
ObjectManager.objects = {};
ObjectManager.register = function (name, object) {
var t = this;
t.objects[name] = object;
}
ObjectManager.getObject = function (name) {
var t = this;
return t.objects[name];
}
function Tab () {
this.name = 'tab object';
}
Tab.prototype.init = function (name) {
var t = this;
t.name = name;
}
Tab.prototype.changeProperty = function () {
var tab1 = ObjectManager.getObject('tab1');
tab1.name = 'changed tab1 name';
}
function Accordion() {
var tab1 = new Tab();
tab1.init('tab number 1');
var tab2 = new Tab();
tab2.init('tab number 2');
ObjectManager.register('tab1', tab1);
ObjectManager.register('tab2', tab2);
console.log(ObjectManager.objects);
tab2.changeProperty();
console.log(ObjectManager.objects);
console.log(tab1.name);
}
var accordion = new Accordion();
虽然我不确定这个解决方案的效率如何,但它可以完成工作