0

I'm learning javascript, I'm new to programming and i was wondering about "this".

let someObject = {
    a : "happy",
    b : "sad",
    c : function(){
        return this.a
    },
    d : this.a
}

someObject.c() returns "happy" but someObject.d returns undefined. why can't it simply assign the value of 'a' to 'd'?

Sigi
  • 1
  • 1
  • 1
    Js is function scoped meaning that when you set d here: `d : this.a` - "this" doesn't refer to `someObject`, it refers to the nearest function scope (or just the global one if not inside any functions). [More info on how 'this' works](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Luke Briggs Apr 10 '22 at 20:40
  • It is not so simple how the keyword "this" is bound in JS. Several rules are applied, described here https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3. – Ilia Yatsenko Apr 10 '22 at 20:46
  • 1
    In short, for current situation, your this is used in global context, so refers to the 'window' object. As window does not have property 'd', it returns undefined. If you put 'this' inside function and put this function in object literal, 'this' starts to refer this object. There are a lot caveats with this in JS, so I advise to read manuals carefully. – Ilia Yatsenko Apr 10 '22 at 20:49

0 Answers0