3

I have an object, which contains lots of other things but I just realised, somehow when I use this I will get undefined or some other things such as this is not a function when it IS a function....

What am I doing wrong here? Can someone please give me a hand?

Here are my sample codes

var global = {
    homepage: '/list/',
    urlRedirect: function (url) {
        window.location.href = url;
    },
    xButtons: this.homepage,
    url: this.urlRedirect('items')
};

console.log(global.xButtons); // gives me undefined
console.log(global.homepage); // gives /list/
global.url // urlRedirect is not a function
Tsuna
  • 2,098
  • 6
  • 24
  • 46
  • 2
    That's not a real OBJECT in JavaScript, you'd need to return it from a function. – flowtron Dec 13 '16 at 09:01
  • 4
    This is because `this` inside an object literal is not equal to this literal. – georg Dec 13 '16 at 09:03
  • 2
    `this` refers to the scope the `global` object was created in (by default the `window`), not the object itself. – Rory McCrossan Dec 13 '16 at 09:04
  • http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ "this" will probably help you, in addiction to what others said there. – briosheje Dec 13 '16 at 09:04

0 Answers0