Jquery create object
Solution 1
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' };
Solution 2
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();
Comments
-
Tom Gullen almost 2 years
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 seem 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();
-
Tim Büthe almost 13 yearsDon't want to start a holy comment war, but aren't semicolons optional in JavaScript? I like this blog posting on this specific topic: mislav.uniqpath.com/2010/05/semicolons
-
DanielB almost 13 yearsYou are right in this one. But you will get errors with i.e. JSLint validation as said in the article ;-). but alright, I will remove that one.
-
Tim Büthe almost 13 yearsYou described, why it isn't neccessary to bin DataBar to "fn", but why bind it to the "$" at all?
-
David Tang almost 13 years@Tim, you don't have to ;) I assumed you wanted it to be related to jQuery somehow, for namespacing or association reasons, so I kept it there.
-
Tim Büthe almost 13 yearsWell, there should be an option for that :-)