Home > Software engineering >  how javascript handles variables in objects?
how javascript handles variables in objects?

Time:07-22

I have a question about declaring a variable in an object. Assuming that global or window is also an object, why is it not possible to declare a variable using let in an object that is a child of the window object? I do not understand that. Thanks for the answer and sorry for the English but I hope you understand the question.

this doesnt worked

let a = 'global';
console.log(a);
const outsideObj = {

    let b = 'outside var',
    logIt() {
        console.log(this);
        console.log(a);
        console.log(this.b)
    }
};

outsideObj.logIt();

this worked

console.log(this);

let a = 'global';
console.log(a);

const outsideObj = {

    b: 'outside var',
    logIt() {
        console.log(this);
        console.log(a);
        console.log(this.b)
    }
};

outsideObj.logIt();

i dont get difference between windows object and regular object why is it possible in parent and not in child?

CodePudding user response:

An object has properties and can be created by an object literal with property definitions.

A scope has variables and can be created by a block statement with variable declarations.

Do not mix these two concepts, especially not syntactically. That global var and function declarations implicitly create properties on the global object is a special case, and also only works by the global object being provided by the runtime - there is no object literal for it.

  • Related