0

I have come across this programming style where: Instead of calling an object method directly, they pass in its constructor method a string, the constructor method then check this string and call the function associate with it.

function MySimpleObject(option){
  if (typeof option === 'String'){
    pluginMethods[String].apply(this, arguments);
  }
  else {
    init();
  }
}

This seem to be used with jQuery as extend function a lot.

jQuery.fn.extend({simpleObj: MySimpleObject});

I would really appreciate if someone could enlighten me on this.

MikeNQ
  • 653
  • 2
  • 15
  • 29
  • 1
    Which part are you not sure about? And shouldn't your code snippet there be `pluginMethods[option].apply(this, arguments);`? – Matt Burland Nov 04 '14 at 20:59
  • Does this help: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Matt Burland Nov 04 '14 at 21:00

1 Answers1

1

This allows the following style of programming, which is used by jQuery UI for example:

$('selector').datepicker('option', 'option-name', 'option-value');

If you call .datepicker() with no arguments or an object, it initializes the datepicker. When the first argument is a string, it's a call to a method of the datepicker. This approach is used for all the jQuery UI widgets, and is common among many other jQuery plugins as well.

Barmar
  • 741,623
  • 53
  • 500
  • 612