Slides from a tutorial I gave at ETech 2006. Notes to accompany these slides can be found here: http://simonwillison.net/static/2006/js-reintroduction-notes.html
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
Slides from a tutorial I gave at ETech 2006. Notes to accompany these slides can be found here: http://simonwillison.net/static/2006/js-reintroduction-notes.html
There are several JavaScript libraries available in the world of web programming. And, as the usage and complexity is increasing day by day, sometimes it becomes very difficult and confusing to understand and create modules using those libraries, especially for those having strong background of Object Oriented Languages.
So this one hour session will make an effort to go into the very basics of JavaScript and put a base for writing modular JavaScript code.
Talk @ RubyConfIndia 2012. Ruby is a pure object oriented and really a beautiful language to learn and practice.
But most of us do not bother to know or care about what happens behind the scene when we write some ruby code. Say creating a simple Array, Hash, class, module or any object. How does this map internally to C code ?
Ruby interpreter is implemented in C and I will talk about the Interpreter API that we as ruby developers
should be aware of. The main purpose of the presentation is to understand the efforts and complexity behind
the simplicity offered. I would also like to touch upon the difference in implementation of some core data structures
in different ruby versions. Having known a part of C language implementation behind Ruby, I would also like to throw some light upon when and why would we need to write some ruby extensions in C.
An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, Objects and prototypal inheritance ideas.
JavaScript - An Introduction is a beginner's guide to JavaScript. It starts with very basic level and goes to intermediate level. You'll be introduced with every language constructs, Event handling, Form handling and AJAX which is supported by JavaScript with XMLHttpRequest object. This XHR object is discussed in enough detail so that you can understand how the underlying AJAX functionality works in jQuery. At the end it discusses advance concepts and library build on/around JavaScript.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
This presentation will give you a brief background to JavaScript, what it is and where it comes from. Then it will walk you through general pitfalls, best practices and more advanced topics such as object-orientation, scope and closures.
The presentation helps us in understanding the different concepts associated with TypeScript. What is TypeScript? Why is TypeScript used and the different applications of TypeScript. For more information you can simply visit: http://mobile.folio3.com/
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...IJSRD
The process by which biomass can be converted to a producer gas by supplying less oxygen than actually required for complete combustion of the fuel is known as gasification. It is a thermo-chemical process and it is performed by a device known as gasifier. For executing the gasification experiments nowadays single throated gasifier uses sugarcane industry waste. In the present study we get to know that sugarcane briquettes are manufactured from residue of sugarcane which is used as a biomass material for the gasification process. Briquettes are formed by extruding the sugar which is extracted from the residue of sugarcane (bagasse) dried in the sun. Equivalence ratio, producer gas composition, calorific value of the producer gas, gas production rate and cold gas efficiency are certain grounds for estimating the performance of the biomass gasifier. The experiential results are compared with those reported in the literature.
Talk @ RubyConfIndia 2012. Ruby is a pure object oriented and really a beautiful language to learn and practice.
But most of us do not bother to know or care about what happens behind the scene when we write some ruby code. Say creating a simple Array, Hash, class, module or any object. How does this map internally to C code ?
Ruby interpreter is implemented in C and I will talk about the Interpreter API that we as ruby developers
should be aware of. The main purpose of the presentation is to understand the efforts and complexity behind
the simplicity offered. I would also like to touch upon the difference in implementation of some core data structures
in different ruby versions. Having known a part of C language implementation behind Ruby, I would also like to throw some light upon when and why would we need to write some ruby extensions in C.
An introductory presentation I'm doing at my workplace for other developers. This is geared toward programmers that are very new to javascript and covers some basics, but focuses on Functions, Objects and prototypal inheritance ideas.
JavaScript - An Introduction is a beginner's guide to JavaScript. It starts with very basic level and goes to intermediate level. You'll be introduced with every language constructs, Event handling, Form handling and AJAX which is supported by JavaScript with XMLHttpRequest object. This XHR object is discussed in enough detail so that you can understand how the underlying AJAX functionality works in jQuery. At the end it discusses advance concepts and library build on/around JavaScript.
Not so long ago Microsoft announced a new language trageting on front-end developers. Everybody's reaction was like: Why?!! Is it just Microsoft darting back to Google?!
So, why a new language? JavaScript has its bad parts. Mostly you can avoid them or workaraund. You can emulate class-based OOP style, modules, scoping and even run-time typing. But that is doomed to be clumsy. That's not in the language design. Google has pointed out these flaws, provided a new language and failed. Will the story of TypeScript be any different?
This presentation will give you a brief background to JavaScript, what it is and where it comes from. Then it will walk you through general pitfalls, best practices and more advanced topics such as object-orientation, scope and closures.
The presentation helps us in understanding the different concepts associated with TypeScript. What is TypeScript? Why is TypeScript used and the different applications of TypeScript. For more information you can simply visit: http://mobile.folio3.com/
Fabrication and Performance Analysis of Downdraft Biomass Gasifier Using Suga...IJSRD
The process by which biomass can be converted to a producer gas by supplying less oxygen than actually required for complete combustion of the fuel is known as gasification. It is a thermo-chemical process and it is performed by a device known as gasifier. For executing the gasification experiments nowadays single throated gasifier uses sugarcane industry waste. In the present study we get to know that sugarcane briquettes are manufactured from residue of sugarcane which is used as a biomass material for the gasification process. Briquettes are formed by extruding the sugar which is extracted from the residue of sugarcane (bagasse) dried in the sun. Equivalence ratio, producer gas composition, calorific value of the producer gas, gas production rate and cold gas efficiency are certain grounds for estimating the performance of the biomass gasifier. The experiential results are compared with those reported in the literature.
An introduction to JavaScript that includes side-by-side comparisons with Python -- for journalism students. Based on the free JavaScript exercises/lessons at Codecademy: http://www.codecademy.com/tracks/javascript (Students in this course spent 4 weeks learning Python before they were introduced to JavaScript.)
Paris Web - Javascript as a programming languageMarco Cedaro
How to setup up a stable javascript continuous integration environment and why you need it. Through a real life example, the talk explains all the benefits of having a development process that brings real control over javascript codebase. A deep analysis of developer and webapps needs and of the tools that fit those requirements.
"Reactive Programming with JavaScript" by Giorgio Natili
JavaScript is an asynchronous and almost single-thread language. Learning how to manage its asynchronous nature is perhaps the most important part of becoming an effective JavaScript programmer. Reactive programming tools in JavaScript provide a powerful way of “wrapping” the asynchronous callbacks into a more readable and maintainable code base. In this talk, I'll highlight the pros and cons of different reactive programming approaches and practices by demonstrating how to use Redux and Angular 2.x as the building blocks of a scalable architecture for your web app.
Interpreted programming or scripting language from Netscape.
Easier to code than the compiled languages like C and C++.
Lightweight and most commonly used script in web pages.
Allow client-side user to interact and create dynamic pages.
Cross-platform and object-oriented scripting language.
Most popular programming language in the world.
JavaScript is arguably the most popular language in the world. It runs in the browser, on the server, on mobile devices, and even powers the Internet of things. In spite of being completely ubiquitous, JavaScript is also the most hated language on the planet.
Unlike other programming languages, JavaScript straddles the line between imperative, object-oriented languages and functional ones. It was originally designed to be a version of the Scheme language for the browser. Which begs the questions, what if we programmed JavaScript functionally?
In this session, we will take a well-known programming problem and first implemented imperatively, then progressively make it more functional. Along the way, we will discuss what makes a language functional.
Best of all we will just use the latest version of JavaScript, ES-2015. No need for any additional libraries. So if you are looking for a different way to code JS, or only curious to learn a bit more about FP, please join us.
An undergraduate project explaining the working and science of a bio-mass gasifier for production of bio-fuel used for heating, cooking and other purposes. Research on the bio-mass gasifier was done at a manufacturing plant in Savli, Gujarat, India.
Esoft Metro Campus - Diploma in Web Engineering - (Module V) Programming with JavaScript
(Template - Virtusa Corporate)
Contents:
Introduction to JavaScript
What JavaScript Can Do?
Script tag in HTML
Noscript tag in HTML
Your First JavaScript Program
JavaScript Placement in HTML File
JavaScript Syntax
JavaScript Data Types
JavaScript Variables
JavaScript Identifiers
Arithmetic Operators
String Concatenation Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
For…in Loop
break Statement
continue Statement
Arrays
Functions
JavaScript Objects
JavaScript Scope
Strings
Regular Expressions
JavaScript Numbers
Math Object
Date and Time
JavaScript Events
Dialog Boxes
Error Handling in JavaScript
JavaScript Forms Validation
JavaScript HTML DOM
JavaScript BOM
JavaScript is lingua franca of the Web. It's pervasive and since 1999 a standard ( ECMAScript 262). Yes, there are other technologies you can use: Flash, Java Applets, Dart, but none of these have the overwhelming support and community that JavaScript does. Over the years it has been maligned as a poorly designed language but I will argue that it has just been misunderstood. This talk will focus on the fundamentals of the language and its integration with the browser, the DOM and server communication via JSON and Ajax.
In the talk Bryan will present:
* Language fundamentals
* Object-Oriented programming
* Functional programming
* DOM APIs
* Event model
* Odds and ends
This Presentation depicts JavaScript concept for Csharp developer.It helps to understand the concepts of JavaScript resembling/differentiate them with C# concepts.
JavaScript and popular programming paradigms (OOP, AOP, FP, DSL). Overview of the language to see what tools we can leverage to reduce complexity of our projects.
This part goes over language features and looks at OOP and AOP with JavaScript.
The presentation was delivered at ClubAJAX on 2/2/2010.
Blog post: http://lazutkin.com/blog/2010/feb/5/exciting-js-1/
Continued in Part II: http://www.slideshare.net/elazutkin/exciting-javascript-part-ii
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2016.
http://www.ivanomalavolta.com
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2015.
http://www.ivanomalavolta.com
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
In this talk we will take a deep dive into the inner workings of JavaScript. Scopes, functions, closures, and prototypes are just some of the most misunderstood terms in the JavaScript world. We will take a tour "behind the scenes" of JavaScript to learn how to write better code.
Lara Technologies are providing Software Training Division, Java/J2ee, Android, Web Services, Logical Coding, Basics Of C Language, Soft Skills, Aptitude, Etc.
By making your site accessible, you'll get a better understanding of HTML semantics, an increased audience reach, Google will reward you... and you will become good looking, admired by your peers, and be the most interesting person in the room.
Like JavaScript, there is a tendency to learn CSS using the View Source technique. This high level overview will focus on what you should do and what you should not do - providing enough CSS knowledge to be dangerous!
This presentation will show the latest Web Components technologies and examples, and whether you should be using Web Components now. (spoiler alert: you should be!)
With great power, comes great responsive-ability web design.
Responsive web design (RWD) will be demystified. Believe it or not, it's more than just media queries, although those will be discussed. It starts with proper UI design and application architecture, and then the dive into CSS - but not too deep! You don't have to be an expert to do RWD, but it helps to have some idea of what you are doing.
Improperly architected applications may work, may perform well, and may meet the acceptance criteria, but the ability to maintain them degrades over time. This presentation will show some of the common mistakes made when building large web applications, how to be aware of them, correct them, and hopefully prevent them.
MVC JavaScript libraries are the hot trendiness right now, and this gives a brief overview of all of the most popular, as well as what exactly is MVC, MVVM, MVP, what they do, and why, or if, we need them.
How to write maintainable JavaScript for web applications: covering everything from syntax and style, to hot loop performance, to application structure.
Dojo has Video and Audio and GFX, so it must be HTML5 compliant, no? Not so fast! We'll look over some core pieces and grade Dojo on how well it holds up!
Especially in small companies, you're often expected to be the end-to-end developer and handle everything from the database to the user interface. This was easy enough in the old days when the UI was little more than a table-based-layout with some sliced graphics. But now with the latest technologies, the front end is becoming just as complex as the back end. In order to get the job done you need to rely more and more upon an ever growing, endless mountain of JavaScript libraries, plugins and boilerplates. Or maybe... you just need a front end developer.
A REST API involves more than just pushing data back and forth between endpoints. This presentation will explain what REST is and also present a variety of topics and questions you will certainly come across while implementing your API.
By Jeremy Brown @notmessenger http://notmessenger.com
A little insight into standards bodies bickering and politics. Is HTML5 is dead? What about that logo? Are we to refer to it as “HTML5″ as the WC3 says or “HTML” as the WHATWG says? When will it be ready? How can we work with no version number?
Are the rumors greatly exaggerated or is HTML5 is dead? What about that logo? Are we to refer to it as "HTML5" as the WC3 says or "HTML" as the WHATWG says? If it's HTML5, when will it be ready? If it's HTML, how can we work to a specification with no version number? A little insight into standards bodies bickering and politics.
How to get a Job as a Front End DeveloperMike Wilcox
For career changers or general job searchers who have experience, and developers in general. Skills and subsets needed to be hirable; How and where to learn FED Skills; Job Search Preparation; Where to find job openings; How to write a resume; How to be a good interview
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
3. Is JavaScript Easy?
★ Scripting languages often considered
simple
★ Loose Typing makes it versatile and
extremely flexible
★ Functional style allows quick tasks:
myDiv.hide();
image.swap();
myForm.validate(); // with script I found on the Internet
4. It is not a Toy!
★ Interpreted language not compiled
★ Loosely Typed
★ OO capabilities
★ Resembles C, C++ and Java in some syntax only
★ Uses prototype for inheritance like Self
5. Mutable
All JavaScript objects,
including the native objects,
can be added to or extended
String.prototype.reverse = function(){
return this.split("").reverse().join("");
}
var a = "Club Ajax";
console.log(a.reverse()); // xajA bulC
6. Mutable
So exactly how “mutable” is
JavaScript anyway?
Array = function(){
alert("JavaScript no longer has Arrays.");
}
var a = new Array("club", "ajax");
8. Object Defined
A JavaScript object is a composite datatype containing an
unordered collection of variables and methods.
★ All objects are a hash map and everything is an object
★ All JavaScript objects are mutable - even the built in
methods and properties can be changed.
★ An object variable is a property - like a field in Java
★ Can contain any type of data - even functions
9. Object Definitions
Creating an object by Definition, using the object’s
constructor function
obj = new Object();
obj.prop = "Club AJAX"
obj.subObj = new Object();
obj.subObj.location = “Dallas”;
obj.subObj.when = new Date("2/3/2009");
10. Object Literals
Creating an object with the Literal syntax - also known
as an initializer
name = {prefix:"Club", suffix:"AJAX"};
obj = {
fullname: name.prefix + name.suffix,
deep:{
fullname: name.prefix + “ “ + name.suffix
}
};
13. Array in Brief
★ An untyped, ordered object
★ Has a length property
★ Additional methods: push(), pop(), etc.
// Definition
var a = new Array(10); // sets length
var b = new Array(“club”, “ajax”); // sets array
// Literal
var c = ["club", "ajax"];
c[2] = "rocks";
// Bad form!
myArray["prop"] = "associative"; // works but unexpected
15. Functions
Unlike Java, Functions are literal data values that can be
manipulated. They can be assigned to variables, properties
of objects, the elements of an array, or passed as
arguments.*
★ Concept borrowed from Lisp Lambda functions
★ Functions are first class objects
★ Functions are objects with executable code
★ Can be used as constructors for object instances**
★ Used as a literal or a definition
* JavaScript - The Definitive Guide
** Function constructors will be covered in the presentation about Inheritance.
17. Function Literal
★ An expression that defines an unnamed function
★ Also called Function Statement or an Anonymous
Function or a Function Expression
★ Much more flexible than Definitions, as they can used
once and need not be named*
// Unnamed Function assigned to "foo":
f[0] = function(x){ return x * x;}
myArray.sort(function(a,b){ return a<b; });
var squared = (function(n){ return n*n })(num);
*JavaScript the Definitive Guide
18. Function Literal Usage
// Stored as a variable:
ar[1] = function(x){ return x * x; }
ar[1](2); // 4
// Passed as an argument:
var add = function( a, b ){
return a() + b();
}
add(function(){ return 1; }, function(){ return 2; }); // 3
// Invoked Directly:
var foo = (function(){ return "bar"; })();
// foo = "bar", the result of the invoked function,
// not the function itself
19. Assigning a Literal to Definition
Allows the body of the function to refer to the Literal
var f = function factor(x, num){
if(x==0){
return num;
}else{
return factor(x-1, num+=x)
}
}
console.log(f(3, 0)); // 6
console.log(factor(3, 0)); // ERROR factor is undefined
20. Function as a Method
A function can be added to any object at any time
var dimensions = {width: 10, height: 5};
dimensions.getArea = function() {
return this.width * this.height;
}
22. Scope
★ Scope is an enclosing context where values and
expressions are associated and is used to define the
visibility and reach of information hiding*
★ JavaScript uses a lexical (or static) scope scheme,
meaning that the scope is created and variables are
bound when the code is defined, not when executed
http://en.wikipedia.org/wiki/Scope_(programming)
23. Scope - Simple Example
★ Functions can see the scope outside them, but not
inside of them
var assassin = "Ninja";
function getWarrior(){
alert(assassin); // SUCCESS!
}
function setWarrior(){
var warrior = "Ninja";
}
alert(warrior); // FAILS!
24. Scope Diagram
The scope chain
resembles a hierarchal
tree, much like that of
classical inheritance scope
scope scope
scope scope scope scope
scope scope scope scope scope
scope scope scope scope
25. Scope Diagram
Like classical
inheritance, the
children can see their
ancestors, but parents scope
cannot see their
descendants scope
scope
scope scope scope scope
scope scope scope scope scope
scope scope scope scope
27. Scope - Objects
★ Objects don’t create a scope (they create context), but
they are able to access scope:
var first = “kick”;
var myObject = {
type:first, // scope captured here
attack: function(){
return this.type;
}
}
alert(myObject.attack());
28. Scope - No Blocks
No block-level scope, unlike C, C++, and Java
function scoping(){
var a = 1;
for(var i=0, len=20; i < len; i++){
if(i==10){
var b = i;
break;
}
}
while(b<20){
b++;
}
console.log(a + i + len + b);
// 51 - no errors, all defined
}
29. Scope - Activation
Variables declared within a function are defined
throughout the function
var hero = "Spider-man"
function scoping(){
alert(hero); // - output ?
var hero = "Dr. Octopus";
alert(hero); // - output ?
}
30. Hey what is var anyway?
The var statement defines a variable by creating a
property with that name in the body of an enclosing
function. If the declaration is not within a function
body, it is declared in the global scope.*
var i;
var x = 10;
var w = 20, y = 30, h = 100;
var f = function(arg){
var a = 1;
var arg = arg + 1; // - result ?
}
*JavaScript the Definitive guide
31. Scope Global
★ In a browser, the window is global
★ Global scope is special because it is the end of the
scope chain, and since it is an object, it has context
★ The following all mean the same thing, in the global
scope only:
<script>
window.weapon = "katana";
weapon = "katana";
var weapon = "katana";
this.weapon = "katana";
</script>
32. Scope Accidental Globals
Regardless of the depth of the scope, not using var
always assigns the variable as a global
transportation = “horse”;
alert("Ninja rides a:", transportation); // - output ?
function ride(){
transportation = "Kawasaki";
alert("Ninja rides a:", transportation); // - ?
}
alert("Ninja rides a:", transportation); // - output ?
34. Context
★ Context is a method’s reference to an object
★ A function and a method are different!
★ A method has context to the object to which it
belongs (a function does not)
★ Whereas scope is lexical and can be determined by
the program code, context is executional, and is
determined at runtime
★ Tip: scope belongs to functions, and context belongs
to objects
35. Context - this
★ A method has a very important keyword: this
★ A method’s value of this becomes the object that
invoked it
★ Context can be thought of as this*
★ this cannot be explicitly set, but it can be changed
★ Change this with either call() or apply()
★ JavaScript libraries usually have convenience
functions to change this
*Execution context actually has a broader meaning that includes scope, which is
an advanced topic.
36. Context vs Scope
★ Context refers to an object and its properties and
methods
★ Scope refers to local functions and variables,
irrespective of the object or its context
var myObject = {
init: function(){
this.myProperty = “prop”;
this.myMethod = function(){ ... }
var myVariable = “value”;
var myFunction = function(){ ... }
}
}
37. Context - Example
var attire = {
ring:"shobo",
init = function(){
return this.ring;
}
}
attire.init(); // context of attire applied to init()
38. "this" is confusing!
If context is not set, regardless of scope, this will
default to the global object
function testNoContext(){
var location = "here";
// local variable, not a context property
alert(this.location);
// returns the window.location object
}
function testNoContext(){
locashion = "TYPO";
alert(location);
// returns the window.location object
}
39. Context - Maintaining
When one object calls another, it can sometimes be
confusing to know in which context you are
var a = {
objectId: "A",
doCall: function(){
return this.objectId;
}
};
var b = {
objectId: "B",
callOther: function(){
return a.doCall();
}
};
alert(b.callOther()); // - result ?
40. Context - Maintaining
Using call() gets a different result
var a = {
objectId: "A",
doCall: function(){
return this.objectId;
}
};
var b = {
objectId: "B",
callOther: function(){
return a.doCall.call(a);
}
};
alert(b.callOther()); // - result ?
41. Context - Changing
Context often "fixed" in "functions" with this pattern:
var self = this;
var myFunc = function(){
self.doMethod();
}
myFunc();
42. dojo.hitch
dojo.hitch changes context for you, using apply() in the
background
myFunc = function(){
this.doMethod();
}
dojo.hitch(this, myFunc)();
// or:
myFunc = dojo.hitch(this, function(){
this.doMethod();
});
43. Context - setTimeout
setTimeout is often awkward due to context. dojo.hitch
fixes this:
setTimeout(dojo.hitch(this, function(){
this.battle = this.doEvil + this.doGood;
this.getConflicted();
}), 500);
44. Context - Anonymous Functions
desc
var o = {
objectId: "A",
docall:function(){
alert(this.objectId);
},
init: function(){
var callCall = dojo.hitch(this, function(){
this.docall();
});
var cc = function(){
this.docall();
}
callCall(); // - result ?
dojo.hitch(this, cc)(); // - result ?
cc.call(this); // - result ?
}
}
46. Closures
★ By definition, closures operate in the execution
context and are a combination of scope and code
★ The result of invoking a function that captures a
variable outside of its scope
★ Closures are not bad - they are quite powerful
★ However:
★ They can consume more memory
★ Creating a circular reference with a DOM node in IE is what
causes memory leaks
47. Closures - Simple Example
saveForLater = function(){
var weapon = “throwing stars”;
return function(){
return weapon; // captures ‘a’
}
}
var device = saveForLater(); // - result ?
setTimeout(function(){
alert(device()); // - result ?
}, 1000);
var doItNow = saveForLater()(); // - result ?
48. Closures - Private Variables
var count = new (function(){
var num = 0;
return function() { return num++ }
})();
alert(count());
alert(count());
alert(count());
49. Memory Leak Example
The onclick function creates a scope and captures the
node variable. The GC can’t remove node because it is
used by onclick, and it can’t remove the DOM
element because the node variable refers to it.
function attach(){
var node = document.createElement("div");
node.onclick = function(){
alert("clicked" + node);
}
}
50. Memory Leak Fixed
The following shows how to do your own GC chores.
Note that most JavaScript libraries will handle this for
you in the background.
function attach(){
var node = document.createElement("div");
node.onclick = function(){
alert("clicked" + node);
}
window.onunload = function(){
node.onclick = null;
window.onunload = null;
}
}
51. dojo.connect
dojo.connect is specifically designed for preventing
for preventing memory leaks
var doClick = function(event){
if(event.type==”onclick”){
alert(“clicked”);
}
}
var node = document.createElement("div");
var ref = dojo.connect(node, “click”, window, doClick);
// when window unloads, dojo will disconnect:
dojo.disconnect(ref);
52. References
JavaScript Closures - Jim Ley
http://www.jibbering.com/faq/faq_notes/closures.html#clIRExSc
Lexical Scoping
http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx
Closures and IE Circular References - Scott Isaacs
http://siteexperts.spaces.live.com/Blog/cns!1pNcL8JwTfkkjv4gg6LkVCpw!338.entry
kartikbansal
http://blogs.msdn.com/kartikb/archive/2009/01/15/lexical-scoping.aspx
WikiPedia
http://en.wikipedia.org/wiki/Scope_(programming)
Mozilla JavaScript Spec
http://www.mozilla.org/js/language/E262-3.pdfs
JavaScript - The Definitive Guide by David Flanagan