Demystifying “this” in JavaScript

If you have worked with Object Oriented languages in the past and then moving to JavaScript, one of the first thing that you need to do is to understand the usage of “this” operator.

this” in other languages that are class-based like C++, Java & C# points to the object that holds the current instance of the class. JavaScript too provides a similar concept using the same this keyword, but beware! – there is a significant difference. In JavaScript functions are first-class objects and they aren’t part of anything else. So the object declared by this (termed as function context) is not determined by how the function is declared but by how it’s invoked. It means the same function can have different contexts depending on how it’s called.

This can be explained by a simple example:

 <script type="text/javascript">

        window.firstName = "WindowFirstName";
        window.lastName = "WindowLastName";

       function fullName(){
            return this.firstName + " " + this.lastName;
        }

        var person1 = new Object();
        person1.firstName = "Steve";
        person1.lastName = "Jobs";
        person1.fullName = fullName;

        var person2 = new Object();
        person2.firstName = "Nish";
        person2.lastName = "Anil";
        person2.fullName = fullName;

       alert(fullName());
       alert(person1.fullName());
       alert(fullName.call(person2));

    </script>

 

In the above code sample notice the function fullName() which returns firstName and lastName and how they access the properties using this operator.  Each alert defined here provides a different output and explains the function context in its true sense! Let’s explore each of the outputs –

alert(fullName())

Here fullName() is accessed as top-level function and remember the top-level functions are properties of window so the function context will be the window itself. In this execution the code will look for firstName and lastName in the window object which is actually set on top with values WindowFirstName & WindowLastName! So the output will be:

image

alert(person1.fullName())

 fullName is a property that is defined within persorn1 object which internally holds the reference of the function fullName. So in this case the function context will be of the calling function person2 and hence it returns values of firstName & lastName defined within the object.

image

alert(fullName.call(person2))

In JavaScript you can explicitly control what’s used as the function context by invoking a function via the Function methods call() &apply().

In this case we are invoking the function using the call() method and specifying the first parameter as it’s function context. person2 is passed to the call() method which set’s the function context as person2.  Hence the output:

image

Hope this post explained “this” in JavaScript and why you should care! You can read more on using this at the Mozilla developer Network documentation.

-Nish

Normalize CSS instead of Reset

Previously I wrote about Why Reset CSS and gave you a code snippet that helps you override browser defaults and set consistency across all.  But I later figured out that it was an age old trick and web has changed a lot since then. Now we need more modern HTML5 alternative to the traditional reset.

Normalize.css is a better alternative to reset because it preserves useful browser defaults rather than erasing them. It has CSS that normalizes HTML5 elements, typography, lists, embedded content, forms and tables.

Have a look at this example on how search field is set consistent across browsers:

 <pre>
  input[type="search"] {
    -webkit-appearance: textfield; /* 1 */
    -moz-box-sizing: content-box;
    -webkit-box-sizing: content-box; /* 2 */
    box-sizing: content-box;
}
</pre>

In addition to normalizing it also corrects common bugs for desktop and mobile browsers which is out of scope for resets.

Simplest difference between the two is that – Reset removes all built-in browser styling and Normalize aims to make built-in browser styling consistent across browsers.

So who’s using it?

Twitter Bootstrap, HTML5 Boilerplate, CSS Tricks and many other frameworks use Normalize CSS.

Further Read

Normalize.css has pretty neat inline documentation and there are additional detail and explanation on their wiki page.

There is also a nice article by @necolas on About Normalize.css which will help you understand the details.

– NishAnil on twitter

‘LESS’– a better way to write CSS

css-less-nnish

Are you a programmer like me who thinks design is a planet just outside your universe? Then you know CSS is fun, exciting and easy until your website grows fat with pages and complicated layouts. If you have ever tried fixing a layout in such a page – you know what I mean. Did I talk about fixing a layout? Oh yeah thanks to all the browsers.

Many at times while writing CSS I wished I could write it more programmatically than just styling them. For e.g. If CSS had allowed variable declarations, I could have simply held the values in variables, perform few operations and re-use them in properties. But that’s too much to ask for from a stylesheet language which should just do styling!

After doing couple of research I came across LESS – The dynamic stylesheet language. I spent a few hours re-styling some of my demos with LESS and I am must say I am thoroughly impressed with it. 

Read more on my Infragistics blog ‘LESS’– A dynamic language that simplifies your CSS

Have a feedback? Let me know @nishanil

by Nishanth Anil

Why reset CSS?

css-reset-nnish

Have you noticed inconsistent rendering of HTML elements in different browsers and have got annoyed with it? This is because all the browsers have presentation defaults but none have the same default. For e.g. the way chrome renders an input type is totally different from the way IE does.  But as a web developer you want your web pages to look same(at least close enough) across browsers. One way is to go fix for every browser in CSS files but another way is to simply reset your html tags to default and the paint them again!

Here’s the code for it:

  <pre>html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}</pre>

Note: Remove the <pre> tag from the above code while pasting.

See Original Source here. And here’s an elaborate reason for CSS reset from Meyerweb.

– Nish

@NishAnil on twitter

How to fallback when jQuery on CDN fail

google_failwhale

Google and Microsoft provide their own Ajax Content delivery network which deliver JavaScript libraries like jQuery, Knockout, Angular etc. for developers for free!

As a web developer you are more than happy to refer them on your web pages and take the full benefit of CDN. But what if they fail? You will simply look bad!

Fortunately there is a simple trick that let’s you fallback to your web server’s JavaScript files.

Check out this blog for details: Simple trick to silently fallback when CDN’s unreachable.

Have a feedback? Let me know @nishanil

JavaScript MV* Framework blog series, Getting Started with BackboneJS

Javascript-MVC-Juggle

 

JavaScript has become one of the most popular programming languages on the web. At first, developers didn’t take it seriously, simply because it was not intended for server side programming. It was a common misconception among professional developers that this language was meant for “Amateurs” as it focused only on User Interface. JavaScript got the spotlight when the usage of Ajax came to light and professional programmers gave importance to the responsiveness of the page. But now the language has become more popular than ever as the User Experience has become the key part of web development. Accessing web is not limited to browsers alone – there are lot many devices with varying screen sizes accessing the same content. With the rise of HTML5 and CSS3 the web will become more adaptive and responsive than ever and JavaScript plays a major role in it. It has also gained popularity in the server side programming which is made possible by NodeJS framework.

Increase in usage of JavaScript in modern applications demand developers to write maintainable code, separate concerns and improve testability. JavaScript is a “class” less language and it was not designed to support Object Oriented Programming, however you can achieve similar results by workarounds. So if you are a developer from an Object Oriented Programming world, then you will find it hard until you get used to it. Though there are some DOM manipulation libraries like jQuery which simplifies client side scripting of HTML, they actually do not solve the problem of effectively handling separation of concerns. You will end up writing lot many jQuery selectors and callbacks to keep the data in sync between the HTML, JavaScript and the data fetched from the server and we’re still stuck with the Spaghetti code.

Fortunately there are a few libraries and frameworks that come to rescue.

What is MV*?

Though all the frameworks out there somewhat tries to be MVC but they do not necessarily follow the pattern strictly. The idea of all the patterns is to separate Model, View and Logic that hooks the two behind which is the controller. However BackboneJS embeds the controller logic in the view itself though it efficiently maintains the separation. On the other side we do have other libraries which implement Model-View-Presenter(MVP) and Model-View-ViewModel(MVVM)pattern. For this reason we will refer these frameworks as MV* implementation.

I kick started a new blog series on my Infragistics Blog which will introduce you to BackboneJS, KnockoutJS, AngularJS and EmberJS JavaScript Frameworks.

Have a look at the first part of this series – Hello Backbone.

Have a feedback? Find me on twitter @nishanil

-Nish

Future belongs to ?

I happened to come across this wonderful image on the internet and it made me think for hours. Thought I must share this with you because it helped me and hope it helps you too!

 

35_10

Image Credits & original source: Forbes

In my opinion one inherent quality of a leader must be getting their hands dirty. When you set out to do that you will have a complete different perspective to your life. You will make things happen at every cost!

Be a leader, be a doer too!

-Nish