Jquery create object
This is a simple question I know, I've looked on google but can't find much help. I'm trying to create an object, with my own custom parameters, and then call one of them in an alert.
Whatever I try, doesn't see开发者_Go百科m to work, I know this is pretty simple stuff and I appologise! All my other JS in my time have been pretty simple and all inline because of that, I'm moving on to more OOP JS now.
$.fn.DataBar = function() {
$.DataBar.defaultOptions = {
class: 'DataBar',
text: 'Enter Text Here'
}
this.greet = function() {
alert(this.text);
};
}
var q = new $.DataBar();
q.greet();
You don't need the
fn
part, simply use:$.DataBar = function () { ... };
$.fn
is simply a reference to jQuery's internal prototype. So$.fn.DataBar
is intended to be used as$(selector).DataBar()
, not$.DataBar()
.Your default options aren't being applied to the newly created object. Optionally, you can also define the
greet
function onDataBar
's prototype:$.DataBar = function () { $.extend(this, $.DataBar.defaultOptions); }; $.DataBar.prototype.greet = function () { alert(this.text); }; $.DataBar.defaultOptions = { class: 'DataBar', text: 'Enter Text Here' };
There are 4 3 problems in your code
- a missing
;
after the default options (not causing the error) - add the default options to the instance with
this.defaultOptions
- call
alert(this.defaultOptions.text)
- instantiate with
$.fn.DataBar()
as you added your class to$.fn
Here your code working:
$.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();
精彩评论