0

I am trying to create an object with selectors inside. The first one is the context selector which I want to use within the object itself. How can I reference this key within the object?

  var options = {
            elements: {
                "context": $('form#someForm'), 
                "someDropdown" : $("#someDropDown", this.context),
                "someContainer" : $('div#someContainer', this.context), 
            },
            constants: {
                buttonImageLocation : 'image.jpg'
            }           
        };

Thanks

Johnathan Au
  • 5,244
  • 18
  • 70
  • 128
  • `"someDropdown" : $("#someDropDown", $('form#someForm')),`?? why try using "`this.context`"? There is perhaps some more in this question. – davidkonrad Sep 11 '14 at 11:36

1 Answers1

1

JavaScript creates for every function a new scope, not for every block. So in your case this refers to the window and since the window has no context, it is undefined. You could do something like:

var options = {
    element: new (function() {
        this.context = $('form#someForm');
        this.someDropdown = $("#someDropDown", this.context);
        ...
        return this;
    })()
}
Florian Gl
  • 5,984
  • 2
  • 17
  • 30
  • Hi thanks, may I ask why there are two brackets at the end () as that would mean it would appear as function() { ... }() – Johnathan Au Sep 11 '14 at 11:44
  • `(function() { ... })()` directly invokes the function. Without invoking it, your element property would be a function, not an object. – Florian Gl Sep 11 '14 at 11:45
  • Hi I've just tried it and it works but I did console.log(options.elements) and it gave me a big list of all the things within the window as opposed to what's just inside the object itself. My question is, would it just be better on performance if I create the context variable outside the object and then reference it? Or does is this new way faster? – Johnathan Au Sep 11 '14 at 11:53
  • When I do console.log it gives me Object{selectors: Window} as opposed to Object{selectors: Object}. I am just questioning the performance of this :) – Johnathan Au Sep 11 '14 at 11:55
  • My bad, forgot the new keyword. Updated my answer. – Florian Gl Sep 11 '14 at 12:01
  • Thank you very much :) This is quite nifty – Johnathan Au Sep 11 '14 at 12:32