Strict Mode In A Browser

Modern browsers have a “strict” mode that you can enable with a very simple command: “use strict”.This is done for backward compatibility reasons with older browsers. When “use strict” is set inside of a function, that function is said to be in strict mode, and strict mode changes the default value of “this”.

  function doStuff(){
    "use strict";
    console.log(this);
  }
  doStuff();

If you examine the output of this function invocation, you’ll notice that “this” comes out as “undefined”. Strict mode, does not provide direct access to the “global” or “window” object via “this”. It turns “this” in to an undefined value.

One of the effects of this change is that you cannot assign attributes to “this”… “this” is undefined, so calling code like “this.foo = bar” would throw an error saying “this” is undefined.

In NodeJS

The last environment that you need to know about at this point, is NodeJS. NodeJS is a server side runtime of the Google V8 JavaScript engine, allowing you to run JavaScript on the server. Since there is no browser in which NodeJS runs, there is no “window” object. There is, however, a “global” object that works similarly to the “window” object in a browser.

NodeJS With Strict Mode

Similar to a modern browser, NodeJS provides “strict mode”. And similarly to how the browser works, NodeJS’ “strict mode” turns the default value of “this” in to an undefined value. Once again, this prevents you from accidentally creating globally accessible values.

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Javascript, Node.Js Tagged with: ,