Home > database >  Assigning one property to another inside jQuery Object Literal
Assigning one property to another inside jQuery Object Literal

Time:01-23

I'm refactoring existing working code in jQuery into jQuery plugin. In the original code, I have several variables which I use to store settings. One of which is referenced in the other:

var className = ".container";
var element   = `<div ></div>`; 

In the plugin code I'm trying to do the same, but inside Object Literal and I'm getting undefined when I reference "className":

$.fn.pluginName = function (options) {

    var defaultSettings = {
        className: ".container",
        element:  function() {
            return `<div ></div>`;
        };
    };

    var settings = $.extend({}, defaultSettings, options);
};

CodePudding user response:

Since you've said you don't control how the element function is called, you can't rely on this within it (unless you use bind, but there's no need here).

I'm assuming options can override defaultSettings.className, so you don't just want to use defaultSettings instead of this.

You can use settings, though:

$.fn.pluginName = function (options) {
    const defaultSettings = {
        className: ".container",
        element: () => {
            return `<div ></div>`;
        },
    };
    const settings = Object.assign({}, defaultSettings, options);
    // ...presumably more code here...
};

Even though it's above const settings in the code, it won't be called until after settings has been initialized with a value.

  • Related