JavaScript “this” at simplest level

In JavaScript “this” thing confuses the beginners as well as experienced ones sometimes. There is lot of stuff on Internet (may be like this one) and almost each book on JavaScript emphasizes on explaining “this“.

Here lets go through very simplest definition (though informal one) which can help us in understanding “this“.

this” is a reference to object to which enclosing method belongs and if there is no enclosing method “this” is global object “window“.

Examples

1. In global context, without enclosing function
console.log(this);
// window….

Here “this” is in global context hence simply it is nothing but reference to “window” object.
2. In global context, within enclosing function

function foo(){
     console.log(this);
}

foo();
// window

Here “this” is in enclosing function which belongs to global object “window” (you can call window.foo() here),
hence here “this” is “window”.

 

3. In enclosing function which is method of some object.

var foo = {
    bar: function (){
        console.log(this);
    }
};

foo.bar();
// foo

Here “this” is in enclosing function “bar” which belongs to object “foo”, hence “this” is a reference to “foo” object.

 

4. Another varient of #3, but with one more level of nesting

var person = {
    name: “Sachin”,
    showName: function () { console.log(this.name); },
    employee: {
        name: “Web Develoepr Sachin”,
        showName: function () { console.log(this.name);}
    }
};

person.showName();
// Sachin

person.employee.showName();
// Web Developer Sachin

Even if this example shows nesting here, but if we simply follow our informal defination “person.showName” method’s “this” is “person” object and “person.employee.showName” method’s “this” is “employee” object.

 

Let me know your comments.

Happy coding 🙂

Advertisements

How to add sass syntax highlighting for sublime

When you are on sublime editor window,

  1. Enter Ctrl  + Shift + P, it will open command window for sublime.
  2. Type “Install Package Control”
  3. Click command “Install Package Control” form the list, it will install the package control for your sublime.
  4. Enter Ctrl + Shift + P, to open the command window. (Select Install Package)
  5. Enter the “sass” to search the sass support packages
  6. Select the appropriate one and click the package to install.
  7. Your done!, you can use these steps to install any package/support for sublime e.g. jade highlighting

Happy coding…. 🙂