Javascript scope chain - javascript

I am trying to optimize my program. I think I understand the basics of closure. I am confused about the scope chain though.
I know that in general you want a low scope (to access variables quickly).
Say I have the following object:
var my_object = (function(){
//private variables
var a_private = 0;
return{ //public
//public variables
a_public : 1,
//public methods
some_public : function(){
debugger;
alert(this.a_public);
alert(a_private);
};
};
})();
My understanding is that if I am in the some_public method I can access the private variables faster than the public ones. Is this correct?
My confusion comes with the scope level of this.
When the code is stopped at debugger, firebug shows the public variable inside the this keyword. The this word is not inside a scope level.
How fast is accessing this? Right now I am storing any this.properties as another local variable to avoid accessing it multiple times.
Thanks very much!

There are many good ways to optimize Javascript.
This is not one of them.
The cost of searching up the scope is minute.
In addition, you're misunderstanding the this keyword.
The this keyword is an implicit parameter to every function, which will either be the global window object, the instance that the function was called on, or the first parameter passed to call or apply.
The this object will refer to a normal Javascript object; its properties have no scope.

First, have you profiled your application and do you know that this code is a bottleneck?
There's no point optimizing this if your applications spends 99.9% of its time doing something else.

Related

Javascript Properties

Please let me know if question is just dumb and not answerable?
I've just started unit testing with javascript. I have been implementing this blog code into my app. I just confused with name argument being passed to function in javascript. If we talk about Java,Php or any other language they take arguments in construct function and is understandable to use within class something like
$vehicle = new Vehicle('argument here');
Class Vehicle {
protected $name;
function __construct($name) {
$this->name = $name; // we can use the property any where in the class
}
}
//Is name Property? Object? or anything else?
//javascript
(function(name) {
"use strict";
function vehicle(modal) {
this.modal = modal || 'Civic 2015';
}
name.vehicle = vehicle; //? ? ?
})(this);//also why using (this) ?
Also an example would be greatly welcomed.
Javascript doesn't have class (really) and so OOP is handled slightly differently to some of the languages you mention. Often you'll see something like this:
function Vehicle(make, color){
this.make = make;
this.color = color;
}
Vehicle.prototype.getMake = function(){
return this.make;
}
var myCar = new Vehicle('ford', 'green');
myCar.getMake(); //'ford'
As shown in this fiddle I made: https://jsfiddle.net/eqf2apwx/
There are many ways to handle JS objects, however, and I'd suggest you google it a bit, particularly 'Crockford Classless' which is a popular way of handling objects.
The function that you are using above is called self-executing immediate functions, "this" inside such functions always points to the global object, because inside functions that were invoked as functions (that is, not as constructors with new) "this" should always point to the global object.
This pattern is useful because it provides a scope sandbox for your initialization code. Think about the following common scenario: Your code has to perform some setup tasks when the page loads, such as attaching event handlers, creating objects, and so on. All this work needs to be done only once, so there’s no reason to create a reusable named function. But the code also requires some temporary variables, which you won’t
need after the initialization phase is complete. It would be a bad idea to create all those variables as globals. That’s why you need an immediate function—to wrap all your code in its local scope and not leak any variables in the global scope
However, in ECMAScript 5 in strict mode, "this" reference doesn't necessarily point to the global object so you have to adopt a different pattern when your code is in strict mode. Therefore, developers usually pass the reference to "this" from the global scope. SO in your case "this" which is passed as an argument to immediate function is a reference to the global "window" object. Also, this pattern makes the code more interoperable in environments outside the browser because you don't need to hardcode "window" inside the immediate function.

Reaching a variable from nested function in Javascript

Can somebody please explain me why the following code works?
function getLastName()
{
fullName.lastName = "World";
}
function writeName()
{
fullName = {};
fullName.firstName = "Hello";
getLastName();
document.write(fullName.firstName + " " + fullName.lastName);
}
writeName();
For some reason, getLastName() can reach local its enclosing method's local state. How can this work? And also should I utilize this feature of Javascript or it is considered as a bad practice? If it is a bad practice, could you please explain why?
You can see the actual code working here at http://jsbin.com/atituk/2/edit
You don't have any local variables, that would require using the var keyword. All your variables are global and can be accessed anywhere within window, which is not considered good practice at all.
You have not used the var keyword against fullName inside the writeName function, you are therefore taking it from the scope outside writeName. It continues up the chain until it reaches the outer most scope, at which point it creates a global.
Globals are, in general, bad practise as they are hard to keep track of and more likely to be overwritten by accident (e.g. in a race condition).
If you were using strict mode this would create an error instead of a global.
You are using all variables of yours as global variables. So all are recognized everywhere. In order to have a better understanding of variable scopes in Javascript have a look at this great example https://stackoverflow.com/a/500459/655316

javascript closure advantages?

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.
Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible.
The advantage of closures in javascript is that it allows you to bind a variable to an execution context.
var closedIn = {};
var f = function(){
closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}
in that example, you have a normal object literal called closedIn. It is accessed in a function. Because of that, javascript knows it has to bring closedIn everywhere it brings the function f, so it is available to f.
The this keyword is tricky. this is always a reference to the execution scope. You can capture the this of one context to use in another context as follows:
var that = this;
var f = function(){
that.somethingOnThat();
// `this` means the scope f, `that` means whatever 'this' was when defined outside of the function
}
This trick can be very useful somethings, if you are coding object oriented javascript and want a callback to have access to some external scope.
To quote from a Javascript book:
"Functions in JavaScript are lexically
rather than dynamically scoped. This
means that they run in the scope in
which they are defined, not the scopee
from which they are executed. When a
function is defined, the current scope
chain is saved and becomes part of the
internal state of the function."
So the clear advantage is that you can bring any object (functions, objects, etc) along with the scope chain as far as is necessary. This is can also be considered a risk, because your apps can easily consume lots of memory if you are not careful.
I think the best phrase to sum up the purpose of closures would be:
Data Encapsulation
With a function closure you can store data in a separate scope, and share it only where necessary.
If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:
(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}());
Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.
I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.
As we know, the variables that are defined in functions, have local scope. We can't access them from outside of the function.
Problem 1:
local variables are created when the function is called and they will be destroyed when the function's task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.
Global variables are available when the program starts and are destroyed when it ends. They are also available throughout the program.
Problem 2:
Since global variables are accessible throughout the program, they are prone to change from everywhere.
What do we want?
We want to have data persistency + data encapsulation.
We can achieve them by using Closures. By using a closure we can have private variables that are available even after a function's task is finished.
Example:
function initCounter() {
let counter = 0;
return function () {
return ++counter;
}
}
// Each counter is persistent
const countJumps = initCounter();
countJumps();
countJumps();
alert("Jumps count is: " + countJumps());
const countClicks = initCounter();
countClicks();
countClicks();
countClicks();
countClicks();
alert("Clicks count is: " + countClicks());
// Each counter is isolated
alert(counter); // Error: counter is not defined

Distinguishing closure and local variables

A local function in the closure declares a variable with the same name which exists in the closure. So, how could we access closure's variable from the local function?
function closure()
{
var xVar;
function func1()
{
var xVar;
// how to distinguish local and closure scopes.
return xVar;
}
return function () { return func1(); };
}
Creating a private object and making private variables as properties of this object could help. But I am wondering if there is a better and neat solution. Can a scope chain help?
I have edited to make it a complete closure. Anyway, closures are not much concern here, it could be considered for inner functions however, there may be a solution with closures somehow.
Thanks
You can't access the scope chain explicitly in JS. Your problem is the age-old one of variable shadowing, but it's that much more maddening because in JS, the scope chain is actually there at runtime, it's just not available for you to access.
You can play some tricks with rejiggering current scope if you use the hated with operator, but that (as well as arguments's caller/callee stuff) really just give you access to objects and functions with their properties. There's no way to say "give me what xVar means in the n-1 runtime scope from right here".
Variables defined in an inner scope hide variable declarations in an outer scope. The "better and neat solution" is not to reuse variable names that way.
In your example the xVar variable is not a closure, because you redefined its scope to each function. To use that variable as a closure continue to declare it with the var command in the closure() function and then do not declare it with the var function in the func1() function. Instead just use the variable immediately in func1().
There is not an easy way to test if a function is a closure or a local variable. You would have to perform some sort of flow control test and then analyze assignments, where assignments occur, and where assignments do not occur. Then you must compare those results. You could write a tool, in JavaScript, to perform that analysis upon a given input and write you a report as output.

JavaScript garbage collection when variable goes out of scope

Does JavaScript support garbage collection?
For example, if I use:
function sayHello (name){
var myName = name;
alert(myName);
}
do I need to use "delete" to delete the myName variable or I just ignore it?
no.
delete is used to remove properties from objects, not for memory management.
JavaScript supports garbage collection. In this case, since you explicitly declare the variable within the function, it will (1) go out of scope when the function exits and be collected sometime after that, and (2) cannot be the target of delete (per reference linked below).
Where delete may be useful is if you declare variables implicitly, which puts them in global scope:
function foo()
{
x = "foo"; /* x is in global scope */
delete x;
}
However, it's a bad practice to define variables implicitly, so always use var and you won't have to care about delete.
For more information, see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
Ignore it - after the sayHello function completes, myName falls out-of-scope and gets gc'ed.
You don't need to do anything Ted, no need to delete this variable.
Refer: http://www.codingforums.com/archive/index.php/t-157637.html
As others mentioned, when the function exits then your variable falls out of scope, as it's scope is just within the function, so the gc can then clean it up.
But, it is possible for that variable to be referenced by something outside the function, then it won't be gc'ed for a while, if ever, as it is still has a reference to it.
You may want to read up on scoping in javascript:
http://www.webdotdev.com/nvd/content/view/1340/
With closures you can create memory leaks, which may be the problem you are trying to deal with, and is related to the problem I had mentioned:
http://www.jibbering.com/faq/faq_notes/closures.html

Categories

Resources