6

As of jQuery 1.9, a widget can inherit from itself. I couldn't find a real-world example of why this would be useful, and frankly the idea of inheriting from oneself breaks my brain. What is the purpose of this feature? What can I do using this feature that I couldn't do previously, or would've been much harder previously?

4

3 回答 3

2

The reason is to redefine the same widget. So, you add new capabilities to it, don't needing to extend it in another object.

In the example presented in the link that you sent:

$.widget("ui.dialog", $.ui.dialog, {
    close: function() {
        if (confirm( "Is it closing time?" )) {
            this._super("close");
        }
    }
});

After the execution of the code above, every dialog that is created will pop a confirm message when the user clicks in the close button and if s/he accepts it, it will close.

于 2012-08-24T13:23:47.650 回答
1

As it is said in the slide you linked us, "this is the ideal way to extend widgets".

Now you can extend a widget without creating a new, "different" widget object ("different" meaning "another name"). You can add a functionality and still use the very same widget object name.

// An incredibly contrived example
$.widget("ui.dialog", $.ui.dialog, {
  close: function() {
    if (confirm( "Is it closing time?" )) {
      this._super("close");
    }
  }
});

As we can see in the example, we can add a feature to the dialog object, which will appear in the already existent dialogs, i.e., you don't need to create a new "extendedDialog" and then change existent code to use the "extendedDialog" object. Instead, the included functionality will be already available and working there.

于 2012-08-24T13:26:15.033 回答
1

This gives you capabilities similar to categories in objective-c, you can add functionality to a class(widget) without having to change the class/widget code itself, or even have access to it's source.

于 2012-08-24T13:26:24.607 回答