开发者

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();


  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().

  2. 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

  1. a missing ; after the default options (not causing the error)
  2. add the default options to the instance with this.defaultOptions
  3. call alert(this.defaultOptions.text)
  4. 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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜