Search code examples
javascriptobjectscopethiscurly-braces

Question about "this" in JavaScript


This may be a newbie question. I've used javascript for years but have only started to get "serious" about it. I have a question about "this"

var defaults = {
    baseId : 'item_',
    baseName : this.baseId
}

console.log('defaults',defaults);

Not sure why defaults.baseName is "undefined" How does one reference stuff in the curly braces? Is it possible, or do I really have to type 'item_' twice?


Solution

  • JavaScript object literal is a syntatic sugar therefore it does not work.

    this; // at point A
    var defaults = {
        baseId : 'item_',
        baseName : this.baseId
    }
    

    translates to

    this; // point A
    var defaults = new Object();
    defaults.baseId = 'item_';
    defaults.baseName = this.baseId; // "this" here is same as "this" at point A
    

    You can use getters and setters.

    {
       baseId: 'item_',
       get baseName() { return this.baseId; },
       set baseName(x) { this.baseId = x }
    }