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.

2
  • 1
    Which part are you not sure about? And shouldn't your code snippet there be pluginMethods[option].apply(this, arguments);? Commented Nov 4, 2014 at 20:59
  • Does this help: stackoverflow.com/questions/4968406/… Commented Nov 4, 2014 at 21:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.