Function As Constructor In Javascript

We can defined a function like this in javascript:

function Foo(v) { this.v = v; }

And if we assign it to a variable like this:

let x1 = Foo(1);

The Foo instance itself is actually bind to global object. And in web browser, the global object is window. We can confirm this by printing out x1 in Chrome Javascript Console:

We can see x1 is undefined, and Foo(1) is actually bound to window object:

So if we want to bind it to a variable, we need the new operator:

let x2 = new Foo(42);

In this way we can assign the Foo instance to x2 variable. Here is the screenshot of the code output:

From above we can see that x2 is a Foo object.

My Github Page: https://github.com/liweinan

Powered by Jekyll and Theme by solid

If you have any question want to ask or find bugs regarding with my blog posts, please report it here:
https://github.com/liweinan/liweinan.github.io/issues