Dmitry Parzhitsky Dmitry Parzhitsky - 5 months ago 8
Javascript Question

Why in this case the inner function has no access to outer variable?

According to this code:

class Thing {
constructor() {
this.bar = (typeof foo !== "undefined"? foo : null); // (3)
}

static create(...args) {
var foo = args[0];
return new Thing();
}
}


the new
Thing
might be created in two ways: either directly with
new Thing
or with
Thing.create()
.

When it is created in the second way, a new variable
string
is declared. Theoretically, it should be visible within all the scope down to the
return
statement, but in the
Thing.constructor()
(which is called within
Thing.create()
) the
string
is not seen. And
Thing.prototype.prop
is always
null
.

Why is it so?




Here it is seen from the
inner()
function:

(function outer() {
var foo = 5;

(function inner() {
alert(foo);
})()
})();

Answer

Theoretically, it should be visible within all the scope down to the return statement

No.

It won't be visible to any function called within the same scope. I will be visible to any function created inside the same scope.

And in this example the constructor() function is in a higher scope than the string variable.

This would work:

class Thing {
    constructor(prop) {
        this.prop = prop;
    }

    static create() {
        return new Thing(arguments[0]);
    }
}

which, by the way, is nothing but syntactic sugar for:

function Thing(prop) {
    this.prop = prop;
}
Thing.create = function () {
    return new Thing(arguments[0]);
};
Comments