Mickel
Mickel

Reputation: 6696

Need help reaching a variable in JavaScript

Can someone please help me understand the scoop of JavaScript variables, and how to reach them?

Imagine the following...

// Namespace declaration
var p = {};

p.result = {

    searchForm: $('#search-form'),
    searchAction: this.searchForm.attr('action'),

    anotherSection: {
        hello: 'Hello ',
        world: this.hello + 'world!'
    }

}

This won't work, and it gives the error saying this.searchForm is undefined. The same error appears in anotherSection as well (ofc).

How can I declare a variable in terms of another variable inside the same namespace?

Upvotes: 0

Views: 148

Answers (4)

Quentin
Quentin

Reputation: 943833

You can't access the properties of an object inside its own literal — they don't exist yet.

Upvotes: 1

SLaks
SLaks

Reputation: 887757

There is no way to refer to an object literal as you're building it.

You need to write the following:

p.result = {
    searchForm: $('#search-form'),
    anotherSection: {
        hello: 'Hello '
    }
}

p.result.searchAction = p.result.searchForm.attr('action');
p.result.anotherSection.world = p.result.anotherSection.hello + 'world!';

Upvotes: 3

Josh Yeager
Josh Yeager

Reputation: 3793

this is an object, so when you use this.searchForm, you are accessing a property of the this object. You just want to access a variable, so you can just use searchForm.

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827666

The this keyword is bound to the function-context, you can't use it in object literals like that.

You could, make functions as "getters":

var p = {};
p.result = {
  searchForm: $('#search-form'),
  getSearchAction: function () {
    return this.searchForm.attr('action');
  },
  anotherSection: {
    hello: 'Hello ',
    getWorld: function () {
      return this.hello + 'world!';
    }
  }
};

Upvotes: 3

Related Questions