Skip to main content

Javascript in all its weirdness: Constructors

Here is another one that has gotten me before, again ECMAScript 5 will take care of this mostly but until then it's tricky

given an object defined like this

var Obj = function(name) {
this.name=name;
};

What will the following do?
var o = new Obj('anewwin');
console.log(o.name);

As guessed, it will print 'anewwin' to the console

How about this?
var o = Obj('anewwin'); // No 'new' this time
console.log(o.name);

This time you get an error saying o.name does not exist. Why? Because Javascript interpreted 'this' inside the function as the global 'window' object instead. To prove this, add the following:

console.log(window.name); // This prints 'anewwin'

So, behind the scenes, in the absence of 'new', javascript is assigning 'this' to the global window object, thus causing confusion. ECMAScript 5 is supposed to stop assigning 'this' to the global object, for everyone's good.

Until then, the recommended fix is to never call without new, or for safety, do the following

function Obj() {
if (!(this instanceof Obj) ) {
return new Obj(); // To protect against invocations not using new, bounces back to this constructor but with proper object syntax
}
// continue with rest...
}

This makes sure the constructor does not mistakenly use the global 'this' object.

Reference: "Javascript Patterns", Stoyan Stefanov

Comments

Popular posts from this blog

Sending Form data to a backend REST API using Axios

This need is incredibly common and useful, and hopefully will save you a lot of time when doing server side calls from your UI application (or even non UI clients like NodeJS applications) Example here is to send a POST request to an endoint /api/item/new (which will create a new item in the database). We will just assume tbhe backend is already setup (it's not relevant to this article). All we need to know is that we can do a POST /api/item/new and send it form data with two pieces of info     name, filter So, if you have a node.js application (I was using Vue-cli generated project, but it does not matter), install 'axios' (a most popular tool to make server calls these days) npm i axios --save OR yarn add axios (my preferred method) Now, in your service JS file (which is generally when I keep all my api calls) do something like this createNew ( name , filter ) { let formData = new FormData (); formData . append ( "name" , ...

How to write and test Node.JS code that performs mutiple async tasks

This is currently WIP, I will fill in more details but it's a good starting version that is still hopefully useful to the reader... Recently I worked on a project that involved scheduling a number of tasks in parallel in Node.js. Running mutiple tasks I used the await-the library to do this. https://github.com/olono/await-the/blob/master/lib/result.js There are multiple ways to solve this kind of problem. Mainly you have to understand the Node.js is a single threaded environment (See Event loop) and how callbacks operate with a library like async or await-the. Basically, here idea was that you write a function that has a callback as its last argument ```   const doTask = async (arg1, callback) {    const results = await doStuffWith(arg1) ;    callback(results); } ``` Then perform this action on multiple inputs in parallel such as by using the excellent async.mapLimit function if you want to limit how many tasks in parallel you want to to...

Javascript in all its weirdness: What is 'this' ?

The this pointer, people's favorite in languages including Javascript was a great source of pain for me when I was developing a Javascript drop down custom component. I learned today that it was 'this' that caused me problems! Generally, 'this' refers to the global object. It also takes on different values based on your scope/context. -In a global constructor, global function and global code, this refers to the global object ( the first should not be the case in strict mode in ECMAScript5) -In a method of an object, 'this' refers to the object // this pointer name='what?'  // same as this.name var p = function () {      console.log(this.name);  // changes the global name, as no var name is defined locally      name = 'again?';      console.log(this.name); } p(); // the global this.name was modified by the function p // Why? because p is a global function, // and this refers to the global object in that functi...