Photo by Dayne Topkin on Unsplash
Maybe one day you were playing in the dev browser in Chrome, and one day come across something that seemed a bit different.
You've printed things out to the console, and something odd appears.
function foo() {
console.log("Hello")
}
foo.prototype
{constructor: ƒ}
Clicking on the arrow for the constructor, will return an object.
{constructor: ƒ}
constructor: ƒ foo()
arguments: null
caller: null
length: 0
name: "foo"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM572:1
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[2]
[[Prototype]]: Object
What on earth are those double brackets [[]]
?
It's the internal property. In JavaScript, objects have an internal property known as Prototype
. You can also see that there is a Scopes
inside of these double brackets as well once clicking inside an object.
Whenever there are [[]]
that appear, it's an internal property that can't be accessed by our code. Both Scopes
and Prototype
are internal properties of the foo
object.
What's pretty cool, and also very helpful when clicking on the Scopes
internal property, is that when working with some concepts, say, a closure, clicking on the scopes property will show the closure itself.
let f;
const g = function() {
const a = 23;
f = function() {
console.log(a * 2);
};
};
g();
f();
console.dir(f)
// Returns
ƒ f()
arguments: null
caller: null
length: 0
name: "f"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM495:3
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[3]
Clicking on the Scopes
internal property, we can see where the closure lives.
[[Scopes]]: Scopes[3]
0: Closure (g) {a: 23}
1: Script {f: ƒ, g: ƒ}
2: Global {0: Window, window: Window, self: Window, docum...
It's pretty cool, isn't it?
Top comments (4)
Wow, this gives a new perspective of how JS engne works. I was perplexed about this same issue few days ago, how closures must have been implemented by JS Engine using OOP, and here you have unraveled that mystery for me. Thank you!
I'm really glad it helped! I only know it because someone else pointed it out to me, and then suddenly things made much more sense.
Might be an idea to point out which browser you are using!
Thanks for pointing that out. Have amended the post.