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();
Another way to make objects in Javascript using JQuery , getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be: var box = {}; // my object var boxes = []; // my array $('div. test'). each(function (index, value) { color = $('p', this).
Introduction to jQuery object. The jQuery object is a collection of DOM elements and behaves like a special array. Everything in jQuery is an object.
Creating a JavaScript ObjectCreate a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
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 on DataBar
'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
;
after the default options (not causing the error)this.defaultOptions
alert(this.defaultOptions.text)
$.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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With