开发者

What is the best way to incorporate simple, utility objects into more complex, specialized objects?

I am developing some basic utility objects in javascript. These are things like:

spinner {
// generates a spinner
}

dialog {
// generates a dialog
}

wysiwyg {
// generates a wysiwyg editable
}

etc.

Once I have amassed a collection of basic utility objects, I would like to create more spe开发者_如何转开发cific, complex objects for working on different sets of data. For example, an object to edit a list of records.

I am wondering: What is the best way to incorporate the functionality of my utility objects, into my more complex, specialized objects?

Multiple inheritance? For example, an object editList which is created from the parents dialog and spinner, and then augmented? Or is it better design practice to generate new instances of my utility objects inside of my more complex objects?

Thanks in advance for your help.


Multiple inheritance is almost never the right answer. What you want to use is composition. For example, if you have a complex UI panel that can have a couple of different dialogs and a wysiwig, you can do something like

function myPanel(width, height) {
  this.saveDialog = new dialog('Save', ...);
  this.loadDialog = new dialog('Load', ...);
  this.editPanel = new wysywig(width, height);

  . . .
  var me = this;
  // Add a Save button to trigger the save dialog;
  this.saveButton = new button("Save", function() { me.saveDialog.display(); });
  this.addButton(saveButton);
}

Since your more complex object is probably not actually a spinner, or a dialog, but rather a component that uses them all in some way, composition is the proper paradigm here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜