Welcome!

AJAX & REA Authors: Elizabeth White, Trevor Parsons, ChandraShekar Dattatreya, Liz McMillan, David H Deans

Related Topics: AJAX & REA, Java, Open Web

AJAX & REA: Article

JavaScript Execution Context, Closure, Eval and “this” Keyword

These are a few key concepts of JavaScript language that developers should know

These are a few key concepts of JavaScript language that developers should know: execution context, activation object, variable instantiation, scoping, closure, eval and “this” keyword. Knowing these would help one tremendously in Ajax development.

For example, when you write an inner function, you know that you can access the local variables defined in the outer function as if they were defined locally. You can also access the global variables. -Why? How does the host environment resolve such variables?

Another example: When you pass arguments to a function, you can access these arguments as if they were locally defined variables. How does this work?

A slightly more involved example that developers must have seem similar code a lot but may not know the “why”:

function outerFunc(outerArg){
   var localVar = 100;

   function innerFunc(innerArg){
      localVar+=100;
       return (outerArg +innerArg + localVar);
    }

   return innerFunc;
}

 var globalVar = outerFunc(200);
 alert(globalVar(300));	//this displays 700
 alert(globalVar(300));	//this displays 800
 globalVar = outerFunc(200)
 alert(globalVar(300));  //this displays 700 again

Why would the 2nd alert box show 800 (means the value of localVar is retained from the first call) while the third alert displays 700 (the value of localVar is not retained from previous calls)? How does it work?

    Key Concepts

  1. Execution Context:
    An execution context is an abstract concept used by the EcmaScript specification and can be conceived (and even implemented) as a set of objects with properties, though not publicly accessible, that encapsulate the context in which a piece of JavaScript code executes. The JavaScript code would rely on its execution context for things like variable resolution and scoping. 

    All JavaScript code executes in an execution context. Global code (code executed inline, normally as a JS file, or HTML page, loads) gets executed in a global execution context (in a browser, the global context is typically the window object), and each invocation of a function (possibly as a constructor) has an associated execution context. Code executed with the eval and setTimeout functions also gets a distinct execution context.

    When a JavaScript function is called, it enters an execution context. If another function is called (or the same function recursively), a new execution context is created and execution enters that context for the duration of the function call. When that called function returns, control returns to the original execution context and the just finished execution context is available for garbage collection except for cases like closure. Thus running JavaScript code forms a stack of execution contexts.

  2. Activation Object and Variable Object :

    1. Activation Object:
      When an execution context is created, an Activation Object is created. The Activation Object can be considered as a normal JavaScript object with accessible named properties, except that it has no prototype and it cannot be directly referenced by javaScript code.This Activation Object is used for storing context related information such as call arguments and variables, etc. so that they are accessible to the new execution context (see more info on this later in this post).

    2. Variable Object and Variable Instantiation:
      ECMA Specification refers to a “Variable Object” for variable instantiation. “Variable Instantiation” is a process that takes place when the JavaScript host environment processes a piece of script so that it can be executed but before executing the script. In this process, the JavaScript engine prepares(”instantiates”) the local variables, local functions declarations, and arguments to the function call etc. so that these variables are accessible during execution.

      The way that variable instantiation works is to instantiate each of the function’s formal parameters, local variables and inner function declarations as named properties of the Variable Object. In the process, named properties of the Variable object are created for each of the function’s formal parameters. If arguments to the function call correspond with those parameters, the values of those arguments are assigned to the properties (otherwise the assigned value is undefined). If there is an inner function declaration, a function object is created. This function object is assigned a property of the Variable object with name corresponding to the function name used in the function declaration. The last stage of variable instantiation is to create named properties of the Variable object that correspond with all the local variables declared within the function.

      The properties created on the Variable object that correspond with declared local variables are initially assigned undefined values during variable instantiation, the actual initialization of local variables does not happen until the evaluation of the corresponding assignment expressions during the execution of the function body code.

      However, it is very important to point out that the Activation object is used as the Variable object. Though conceptually they are called out as different objects, they are the same object in reality. This is important as you can see quickly in “scope and scope chain” and “variable resolution” later on.

      It is the fact that the Activation object, with its arguments property, and the Variable object, with named properties corresponding with function local variables, are the same object, that allows the identifier arguments to be treated as if it were a function local variable.

More Stories By Coach Wei

Coach Wei is founder and CEO of Yottaa, a web performance optimization company. He is also founder and Chairman of Nexaweb, an enterprise application modernization software company. Coding, running, magic, robot, big data, speed...are among his favorite list of things (not necessarily in that order. His coding capability is really at PowerPoint level right now). Caffeine, doing something entrepreneurial and getting out of sleeping are three reasons that he gets up in the morning and gets really excited.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@CloudExpo Stories
SYS-CON Media announced today that Sematext launched a popular blog feed on DevOps Journal with over 6,000 story reads over the weekend. DevOps Journal is focused on this critical enterprise IT topic in the world of cloud computing. DevOps Journal brings valuable information to DevOps professionals who are transforming the way enterprise IT is done. Sematext is a globally distributed organization that builds innovative Cloud and On Premises solutions for performance monitoring, alerting an...
SYS-CON Events announced today that Cloudian, Inc., the leading provider of hybrid cloud storage solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Cloudian, Inc., is a Foster City, California - based software company specializing in cloud storage software. The main product is Cloudian, an Amazon S3-compliant cloud object storage platform, the bedrock of cloud computing systems, that enables c...
ScriptRock makes GuardRail, a DevOps-ready platform for configuration monitoring. Realizing we were spending way too much time digging up, cataloguing, and tracking machine configurations, we began writing our own scripts and tools to handle what is normally an enormous chore. Then we took the concept a step further, giving it a beautiful interface and making it simple enough for our bosses to understand. We named it GuardRail after its function - to allow businesses to move fast and stay sa...
Leysin American School is an exclusive, private boarding school located in Leysin, Switzerland. Leysin selected an OpenStack-powered, private cloud as a service to manage multiple applications and provide development environments for students across the institution. Seeking to meet rigid data sovereignty and data integrity requirements while offering flexible, on-demand cloud resources to users, Leysin identified OpenStack as the clear choice to round out the school's cloud strategy. Additional...
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, p...
SYS-CON Events announced today Isomorphic Software, the global leader in high-end, web-based business applications, will exhibit at SYS-CON's DevOps Summit 2015 New York, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Isomorphic Software is the global leader in high-end, web-based business applications. We develop, market, and support the SmartClient & Smart GWT HTML5/Ajax platform, combining the productivity and performance of traditional desktop software ...
In high-production environments where release cycles are measured in hours or minutes — not days or weeks — there's little room for mistakes and no room for confusion. Everyone has to understand what's happening, in real time, and have the means to do whatever is necessary to keep applications up and running optimally. DevOps is a high-stakes world, but done well, it delivers the agility and performance to significantly impact business competitiveness.
"Our premise is Docker is not enough. That's not a bad thing - we actually love Docker. At ActiveState all our products are based on open source technology and Docker is an up-and-coming piece of open source technology," explained Bart Copeland, President & CEO of ActiveState Software, in this SYS-CON.tv interview at DevOps Summit at Cloud Expo®, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover ...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com...
Verizon Enterprise Solutions is simplifying the cloud-purchasing experience for its clients, with the launch of Verizon Cloud Marketplace, a key foundational component of the company's robust ecosystem of enterprise-class technologies. The online storefront will initially feature pre-built cloud-based services from AppDynamics, Hitachi Data Systems, Juniper Networks, PfSense and Tervela. Available globally to enterprises using Verizon Cloud, Verizon Cloud Marketplace provides a one-stop shop fo...
The move in recent years to cloud computing services and architectures has added significant pace to the application development and deployment environment. When enterprise IT can spin up large computing instances in just minutes, developers can also design and deploy in small time frames that were unimaginable a few years ago. The consequent move toward lean, agile, and fast development leads to the need for the development and operations sides to work very closely together. Thus, DevOps become...
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada...
SYS-CON Events announced today that AIC, a leading provider of OEM/ODM server and storage solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. AIC is a leading provider of both standard OTS, off-the-shelf, and OEM/ODM server and storage solutions. With expert in-house design capabilities, validation, manufacturing and production, AIC's broad selection of products are highly flexible and are conf...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's

AppZero has announced that its award-winning application migration software is now fully qualified within the Microsoft Azure Certified program. AppZero has undergone extensive technical evaluation with Microsoft Corp., earning its designation as Microsoft Azure Certified. As a result of AppZero's work with Microsoft, customers are able to easily find, purchase and deploy AppZero from the Azure Marketplace. With just a few clicks, users have an Azure-based solution for moving applications to the...
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The cloud is becoming the de-facto way for enterprises to leverage common infrastructure while innovating and one of the biggest obstacles facing public cloud computing is security. In his session at 15th Cloud Expo, Jeff Aliber, a global marketing executive at Verizon, discussed how the best place for web security is in the cloud. Benefits include: Functions as the first layer of defense Easy operation –CNAME change Implement an integrated solution Best architecture for addressing network-l...