Javascript Questions Set4

Global Variables:
The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable.

Types in Javascript:
JavaScript is a loosely-typed language (some call this weakly typed); this means that no type declarations are required when variables are created. Strings and numbers can be intermixed with no worries. JavaScript is smart, so it easily determines what the type should be. The types supported in JavaScript are: Number, String, Boolean, Function, Object, Null, and Undefined.

What does “this” refer to in Javascript?
In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack.

Every line of JavaScript code is run in an “execution context.” The JavaScript runtime environment maintains a stack of these contexts, and the top execution context on this stack is the one that’s actively running.

There are three types of executable code: Global code, function code, and eval code. Roughly speaking, global code is code at the top level of your program that’s not inside any functions, function code is code that’s inside the body of a function, and eval code is global code evaluated by a call to eval.

The object that this refers to is redetermined every time control enters a new execution context and remains fixed until control shifts to a different context. The value of this is dependent upon two things: The type of code being executed (i.e., global, function, or eval) and the caller of that code.

That’s it! You can figure out what object this refers to by following a few simple rules:

– By default, this refers to the global object.
– When a function is called as a property on a parent object, this refers to the parent object inside that function.
– When a function is called with the new operator, this refers to the newly created object inside that function.
– When a function is called using call or apply, this refers to the first argument passed to call or apply. If the first argument is null or not an object, this refers to the global object.

Why to use call and apply instead of calling a function directly ?
You use call or apply when you want to pass a different this value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call expects parameters separated by commas, while apply expects parameters in an array.

Leave a Reply