Christofer Eliasson
Christofer Eliasson

Reputation: 33865

Are class declarations subject to scope in JavaScript?

Thinking about how JavaScript uses functions for scoping of variables, I started to think about what would happen in case of the following example:

var OuterClass = function () {

    var InnerClass = function () {
        this.foo = "bar";
    };

    this.getInstanceOfInner = function () {
        return new InnerClass();
    };

};

var instanceOfOuter = new OuterClass();
console.log(instanceOfOuter.getInstanceOfInner());

Fiddle of the above

Testing the above code in different browsers, the outcome varies:

I got somewhat confused about this, what is the deal here? Are class declarations subject to scope, the same way other variables are? Or is it up to each vendor to implement it as they please?

Upvotes: 2

Views: 101

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

There are no classes and instances in JavaScript, just prototypes and constructor functions (read about the differences here). Those follow the same scoping rules as any other objects. So the constructor function InnerClass itself is not available outside of ÒuterClass but the returned "instance" knows its prototype and browsers may or may not log that.

Upvotes: 3

Related Questions