Creating a jquery object

This is a simple question that I know, I looked at Google, but can not find much help. I am trying to create an object with my own parameters, and then call one of them in the message.

No matter what I try, it does not seem to work, I know that this is a fairly simple material, and I attribute it! Because of this, all my other JSs were pretty simple and all built-in, now I'm moving on to more OOP JS.

$.fn.DataBar = function() { $.DataBar.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' } this.greet = function() { alert(this.text); }; } var q = new $.DataBar(); q.greet(); 
+8
javascript function jquery object
source share
2 answers
  • You don't need the fn part, just use:

     $.DataBar = function () { ... }; 

    $.fn is just a reference to the internal jQuery prototype. Therefore, $.fn.DataBar supposed to be used as $(selector).DataBar() , not $.DataBar() .

  • The default settings do not apply to the newly created object. Optionally, you can also define the greet function on the DataBar prototype:

     $.DataBar = function () { $.extend(this, $.DataBar.defaultOptions); }; $.DataBar.prototype.greet = function () { alert(this.text); }; $.DataBar.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' }; 
+10
source share

In your code <problems> 4 3

  • absent ; after the default settings (without causing an error)
  • add default options to instance using this.defaultOptions
  • call alert(this.defaultOptions.text)
  • create an instance of $.fn.DataBar() when you added your class to $.fn

Here your code works:

 $.fn.DataBar = function() { this.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' }; this.greet = function() { alert(this.defaultOptions.text); }; }; var q = new $.fn.DataBar(); q.greet(); 
+2
source share

All Articles