1

I'm looking through the following code of what I assume could be called a jquery plugin:

H5P.Summary = (function ($, Question) {

  function Summary(options, contentId, contentData) {

    if (!(this instanceof H5P.Summary)) {
      return new H5P.Summary(options, contentId);
    }

It seems to create a Summary object but checks if it is an instance of itself first. Could someone please explain to me why it does this and what the purpose of the return statement is?

Source code on github:

https://github.com/h5p/h5p-summary/blob/master/js/summary.js#L3

The plugin itself:

https://h5p.org/summary

I'm still fairly new to the web dev space, so corrections and simple explanations are welcome.

timothyylim
  • 1,399
  • 2
  • 14
  • 32

1 Answers1

1

To me it looks like the plugin checks whether a new Object needs to be created and returned, if the context already is a summery object, it doesn't need to be created and returned, instead the properties get set with the options in the parameters.

The purpose is that the function can both create and update objects.

user3154108
  • 1,264
  • 13
  • 23
  • 1
    Thanks for your explanation - it makes a lot of sense now. Just one more thing, wouldn't returning a new summary object just jump out of the logic? i.e. how would the other lines be processed once a new object is returned? – timothyylim Jul 21 '16 at 11:15
  • It's a recursion, the function is called in itself as return value (and this time as an object due to `new` keyword). That also is the reason why this enables the object to the created in an assignment without `new` keyword as is described in the link eskimo commented to your question. – user3154108 Jul 21 '16 at 11:27