wonderfan / javascript

Explore the power of HTML,CSS and JavaScript
1 stars 0 forks source link

How to understand the Constructor attribute ? #1

Closed wonderfan closed 9 years ago

wonderfan commented 9 years ago

In the jQuery framework, the plugin function usually has one attribute named Constructor and it is function type. What is its purpose?

for example:

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.scrollspy')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.scrollspy

  $.fn.scrollspy             = Plugin
  $.fn.scrollspy.Constructor = ScrollSpy
gimm commented 9 years ago

At the first glance, I thought it was something related to Object.prototype.constructor, but it's not. The Constructor here has nothing to do with Javascript language itself, I believe it's some pattern, convention or best practice.

I didn't do jquery plugins for years, but here's a piece of info might help essential-jquery-plugin-patterns.

If you insist, you can share the full source of the plugin with a gist, so I can look into the internals, and try to figure it out.

wonderfan commented 9 years ago

It is boostrap ScrollSpy and you can read it in the boostrap code repository directly

wonderfan commented 9 years ago

I think it should be lower case instead of upper case. When creating the JavaScript instance, it will use new keyword and constructor to initialize the object.