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());
Testing the above code in different browsers, the outcome varies:
- Chrome: Logs an instance of the inner-class and seems to be aware of the class declaration.
- Firefox: Seems to log an “untyped” object, but with the correct properties.
- IE9: Logs the string-representation of an object
[object Object]
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?
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
InnerClassitself is not available outside ofÒuterClassbut the returned “instance” knows its prototype and browsers may or may not log that.