The document discusses JavaScript closures. It explains that a closure occurs when an inner function is returned from an outer function and still has access to the outer function's variables even after it has returned. This is because closures combine a function and the environment in which that function was created, including any local variables that were in scope. As a result, the inner function can access and use those variables even though the outer function has finished executing. An example is provided to demonstrate how a function can return another function that still has access to the outer function's variables through a closure.
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
In JavaScript, almost "everything" is an object.
-Booleans can be objects (if defined with the new keyword)
-Numbers can be objects (if defined with the new keyword)
-Strings can be objects (if defined with the new keyword)
-Dates are always objects
-Maths are always objects
-Regular expressions are always objects
-Arrays are always objects
-Functions are always objects
-Objects are always objects
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
This was a presentation I wrote for a previous employer, aimed at Java developers. The goal was to help them understand some of the new UI conventions I was putting into their application, so that they would be able to develop "smarter" JSP code.
JavaScript language plays a very important role in Web 2.0 application development. JavaScript has its own characteristics different than object-oriented languages and it's not easy for developers to understand.
This presentation covers major advanced topics in JavaScript languages, including prototype chain, identifier resolving, "this" keyword, "new" operator, execution context and scope chain and closure. Besides that, it also covers best practices when using JavaScript.
This was a presentation I wrote for a previous employer, aimed at Java developers. The goal was to help them understand some of the new UI conventions I was putting into their application, so that they would be able to develop "smarter" JSP code.
Understanding Object Oriented Javascript - Coffee@DBG JuneDeepu S Nath
You all might have downloaded and edited a lot of javascript. Other than merely changing syntax have you really understood its working or how the code was organised ?
Have you ever thought of how the object oriented way of writing Javascript has been influencing the front end development?
From a language that had helped developers write small validations and similar stuff, today, the object oriented javascript and its frameworks power the world becoming one of the most prominent language of all times.
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
Miller Columns (used in iPhone and Mac Finder) are an elegant way of displaying and navigating a tree. This talk describes a JavaScript implementation of Miller Columns, and why JavaScript needs modules and a standard library.
Similar to Javascriptinobject orientedway-090512225827-phpapp02 (20)
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
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.
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
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.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
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.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
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.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
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.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
2. 2
Agenda
Introduction to JavaScript
Working with Objects
Working with Functions
Working with Closures
Details of the Object Model
Public Members
Private Members
Privileged Members
Static Members
Inheritance
Practical Closures
4. 4
IntroductiontoJavaScript
JavaScript has a reasonable claim to being the
world’s most misunderstood programming
language.
JavaScript is a scripting language most often used
for client-side web development.
Major implementations are SpiderMonkey, Rhino,
KJS, JavaScriptCore, and V8.
It is a dynamic, weakly typed, prototype-based
language with first-class functions.
5. 5
DynamicLanguage
A high level of programming languages that
execute many common behaviors at runtime.These
behaviors could include:
Extension of the program,
By adding new code,
By extending objects and definitions,
Or by modifying the type system.
Dynamic languages and dynamic typing are not
identical concepts, and a dynamic language need
not be dynamically typed, though many dynamic
languages are dynamically typed.
6. 6
ALooselyTypedLanguage
In JavaScript, you do not declare a type when defining a
variable. However, this does not mean that variables are not
typed. Depending on what data it contains, a variable can
have one of several types.
A variable can change its type, depending on what value is
assigned to it.The primitive datatypes can also be cast from
one type to another.
There are three primitive types: booleans, numbers, and
strings.
There are functions, which contain executable code.There
are objects, which are composite datatypes.
Lastly, there are the null and undefined datatypes. Primitive
datatypes are passed by value, while all other datatypes are
passed by reference.
7. 7
Prototyped-basedProgramming
A style of object-oriented programming in which
classes are not present, and behavior reuse (known
as inheritance in class-based languages) is
performed via a process of cloning existing objects
that serve as prototypes.This model can also be
known as class-less, prototype-oriented or instance-
based programming.
In prototype-based systems there are two methods
of constructing new objects, through cloning of an
existing object, and through ex nihilo ("from
nothing") object creation.
8. 8
LanguageFeatures
Structured
JavaScript supports all the structured programming syntax in C (e.g., if
statements, while loops, switch statements, etc.). One partial exception is
scoping:C-style block-level scoping is not supported. JavaScript 1.7, however,
supports block-level scoping with the let keyword. Like C, JavaScript makes a
distinction between expressions and statements.
Dynamic
dynamic typing
Types are associated with values, not variables.
JavaScript supports duck typing.
objects as associative arrays
JavaScript is heavily object-based. Objects are associative arrays. Properties
and their values can be added, changed, or deleted at run-time.
run-time evaluation
JavaScript includes an eval function that can execute statements provided as
strings at run-time.
9. 9
LanguageFeatures(cont.)
Functional
first-class functions
Functions are first-class; they are objects themselves. As such, they have
properties and can be passed around and interacted with like any other objects.
first-class functions treats functions as first-class objects. Specifically, this
means that the language supports constructing new functions during the
execution of a program, storing them in data structures, passing them as
arguments to other functions, and returning them as the values of other
functions.
inner functions and closures
Inner functions (functions defined within other functions) are created each
time the outer function is invoked, and variables of the outer functions for that
invocation continue to exist as long as the inner functions still exist, even after
that invocation is finished (e.g. if the inner function was returned, it still has
access to the outer function's variables) — this is the mechanism behind closures
within JavaScript.
10. 10
LanguageFeatures(cont.)
Prototype-based
prototypes
JavaScript uses prototypes instead of classes for defining object properties,
including methods, and inheritance. It is possible to simulate many class-based
features with prototypes in JavaScript.
functions as object constructors
Functions double as object constructors along with their typical role.
Prefixing a function call with new creates a new object and calls that function
with its local this keyword bound to that object for that invocation. The function's
prototype property determines the new object's prototype.
functions as methods
Unlike many object-oriented languages, there is no distinction between a
function definition and a method definition. Rather, the distinction occurs during
function calling; a function can be called as a method. When a function is invoked
as a method of an object, the function's local this keyword is bound to that object
for that invocation.
11. 11
LanguageFeatures(cont.)
Others
run-time environment
JavaScript typically relies on a run-time environment (e.g. in a web browser)
to provide objects and methods by which scripts can interact with "the outside
world". (This is not a language feature, but it is common in most JavaScript
implementations.)
variadic functions
An indefinite number of parameters can be passed to a function. The
function can both access them through formal parameters and the local
arguments object.
array and object literals
Like many scripting languages, arrays and objects (associative arrays in
other languages) can be created with a succinct shortcut syntax. The object literal
in particular is the basis of the JSON data format.
regular expressions
JavaScript also supports regular expressions in a manner similar to Perl.
13. 13
Objects
JavaScript is fundamentally about objects. Array
are objects. Functions are objects. Objects are
objects.
What are objects?
Objects are collections of name-value pairs.The
names are strings, and the values are string,
numbers, booleans, and objects.
14. 14
ObjectsandProperties
You define a property of an object by assigning it a value.
myCar.make = “Ford”;
JavaScript objects are sometimes called associative arrays,
since each property is associated with a string value that can
be used to access it.
Properties of JavaScript objects can be accessed or set using
a dot notation or bracket notation.
myCar.make = “Ford”;
or myCar[“make”] = “Ford”;
or var propertyName = “make”;
myCar[propertyName] = “Ford”;
15. 15
ObjectsandProperties(cont.)
You can use the bracket notation with for…in to iterate
over all the properties of an object.
function showProperties(obj, objName) {
var result = “”;
for(var i in obj)
result += objName + “.” + i + “ = “ + obj[i] + “n”;
return result;
}
myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969
16. 16
CreatingNewObjects
You can create an object using an object
initializer.
var obj = { property_1: value_1,
property_2: value_2,
property_n: value_n };
Alternatively, you can create an object with
these two steps:
1. Define the object type by writing a constructor
function.
2. Create an instance of the object with new.
17. 17
CreatingNewObjects(cont.)
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Now, you can create an object called myCar as follows:
myCar = new Car(“Eagle”, “Talon TSi”, 1993);
You can create any number of car objects by calls to new.
An object can have a property that is itself another object.
18. 18
IndexingObjectProperties
In JavaScript 1.1 or later,
if you initially define a property by its name, you
must always refer to it by its name,
myCar.color = “red”;
and if you initially define a property by an index,
you must always refer to it by its index.
myCar[5] = “25 mpg”;
19. 19
DefinePropertiesforanObjectType
You can add a property defined object by using
the prototype property.
Car.prototype.color = “red”;
car1.color = “blue”;
This defines a property that is shared by all
objects of the specified type, rather than by just
one instance of the object.
20. 20
DefineMethods
A method is a function associated with an
object.You define a method by:
object.methodname = function_name;
You can then call the method in the context of
the object as follows:
object.methodname(params);
22. 22
DeletingProperties
You can remove a property by using the delete operator.
//create a new object with two properties: a and b.
myObj = new Object();
myObj.a = 5;
myObj.b = 12;
delete myObj.a; //remove the a property
24. 24
FunctionObject
A JavaScript function can take 0 or more named
parameters.
The function body can declare its own variables
which are local to that function.
If no return statement is used, JavaScript returns
undefined.
function add(x, y) {
var total = x + y;
return total;
}
25. 25
FunctionsAsFirst-ClassObjects
In JavaScript, functions are first-class objects.They can be
stored in variables, passed into other functions as
arguments, passed out of functions as return values, and
constructed at run-time.
You can create anonymous functions, which are functions
created using the function() { ... } syntax.They are not given
names, but they can be assigned to variables.
JavaScript has function-level scope.
JavaScript is also lexically scoped, which means that
functions run in the scope they are defined in, not the scope
they are executed in.
26. 26
FunctionArguments
JavaScript functions can be invoked with any
number of arguments, regardless of the number of
arguments named in the function definition.
You can call a function without passing the
parameters it expects, in which case they will be set
to underfined.
add(); //NaN
You can also pass in more arguments than the
function is expecting:
add(2, 3, 4); //5
27. 27
Theargumentsobject
Functions have access to an additional variable
inside their body called arguments, which is an
array-like object holding all of the values passed to
the function.
function add() {
var sum = 0;
for(var i=0; i<arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
add(2, 3, 4, 5); //14
28. 28
Theargumentsobject(cont.)
The arguments object defines a callee property
that refers to the function that is currently being
executed.This property is rarely useful, but it can be
used to allow unnamed functions to invoke
themselves recursively.
function(x) {
if (x <= 1) return 1;
return x * arguments.callee(x-1);
}
29. 29
FunctionsasData
In JavaScript, however, functions are also data, which means
that they can be assigned to variables, stored in the
properties of objects or the elements of arrays, passed as
arguments to functions, and so on.
function square(x) { return x*x; }
var a = square(4); // a contains the number 16
var b = square; // Now b refers to square
var c = b(5); // c contains the number 25
var o = new Object();
o.square = function(x) { return x*x; }
y = o.square(16); // y equals 256
30. 30
ConstructorFunctions
A constructor function is a function that
initializes the properties of an object and is
intended for use with the new operator.
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
31. 31
FunctionPropertiesandMethods
The length property of the arguments array specifies the
number of arguments that were passed to the function.
The length property of the Function object returns exactly
how many declared parameters a function has.
Note that unlike arguments.length, this length property is
available both inside and outside of the function body.
function check(args) {
var actual = args.length;
var expected = args.callee.length;
if (actual != expected) {
throw new Error("Wrong number of arguments:
expected: " + expected + "; actually passed " + actual);
}
}
32. 32
DefiningYourOwnFunctionProperties
When a function needs to use a variable whose
value persists across invocations, it is often
convenient to use a property of the Function object,
instead of cluttering up the namespace by defining
a global variable.
function counter() {
if (!arguments.callee.count) {
arguments.callee.count = 0;
}
return arguments.callee.count++;
}
33. 33
Theapply() andcall() Methods
These methods allow you to invoke a function as if it
were a method of some other object.
The first argument to both call() and apply() is
the object on which the function is to be invoked;
this argument becomes the value of the this
keyword within the body of the function.
Any remaining arguments to call() are the values
that are passed to the function that is invoked.
34. 34
Theapply() andcall() Methods
f.call(o, 1, 2);
This is similar to the following lines of code:
o.m = f;
o.m(1,2);
delete o.m;
The apply() method is like the call() method,
except that the arguments to be passed to the
function are specified as an array:
f.apply(o, [1, 2]);
35. 35
AnonymousFunctions
An anonymous function, executed immediately.
(function() {
var foo = 10;
var bar = 2;
alert(foo * bar);
})();
An anonymous function with arguments.
(function(foo, bar) {
alert(foo * bar);
})(10, 2);
An anonymous function that returns a value.
var baz = (function(foo, bar) {
return foo * bar;
})(10, 2);
36. 36
AnonymousFunctions(cont.)
Here’s a way of “hiding” some local variables – like
block scope in C:
> var a = 1;
> var b = 2;
> (function() {
var b = 3;
a += b;
})();
> a
4
> b
2
37. 37
InnerFunctions
JavaScript function declarations are allowed inside
other functions.
An important detail of nested functions in
JavaScript is that they can access variables in their
parent function’s scope.
function betterExampleNeeded() {
var a = 1;
function oneMoreThanA() {
return a + 1;
}
return oneMoreThanA();
}
39. 39
WorkingwithClosures
Closures are often considered an advanced feature in JavaScript, but
understanding them is essential to mastering the language.
JavaScript allows inner functions.
And that those inner functions are allowed access to all of the local
variables, parameters and declared inner functions within their outer
function(s).
A closure is formed when one of those inner functions is made accessible
outside of the function in which it was contained, so that it may be
executed after the outer function has returned.
At which point it still has access to the local variables, parameters and
inner function declarations of its outer function.
41. 41
WorkingwithClosures(cont.)
This is an example of lexical scoping: in JavaScript, the
scope of a variable is defined by its location within the
source code, and nested functions have access to
variables declared in their outer scope.
Now consider the following example:
function makeFunc() {
var name = “Mozilla”;
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
42. 42
WorkingwithClosures(cont.)
The displayName() inner function was
returned from the outer function before being
executed.
Normally, the local variables within a function
only exist for the duration of that function’s
execution. Once makeFunc() has finished
executing, it is reasonable to expect that the
name variable will no longer be necessary.
Since the code still works as expected, this is
obviously not the case.
43. 43
WorkingwithClosures(cont.)
A closure is a special kind of object that combines
two things: a function, and the environment in
which that function was created.
The environment consists of any local variables that
were in-scope at the time that the closure was
created.
In this case, myFunc is a closure that incorporates
both the displayName() and the “Mozilla” string
that existed when the closure was created.
45. 45
AMoreInterestingExample(cont.)
We have defined a function makeAdder(x) which takes a
single argument x and returns a new function.The function
it returns takes a single argument y, and returns the sum of
x and y.
In essence, makeAdder is a function factory – it creates
functions which can add a specific value to their argument.
• add5 and add10 are both closures.They share the same
function body definition, but store different environments.
In add5’s environment, x is 5. In add10’s environment, x is
10.
47. Class-Basedvs.Prototype-Based
Languages
Class-Based Prototype-Based
Class and instance are
distinct entities.
Define a class with a class
definition; instantiate a
class with constructor
methods.
Create a single object with
new operator.
All objects are instances.
Define and create a set of
objects with constructor
functions.
Same.
48. Class-Basedvs.Prototype-Based
Languages(cont.)
Construct an object
hierarchy by using class
definitions to define
subclasses of existing
classes.
Inherit properties by
following the class chain.
Class definition specifies all
properties of all instances
of a class. Cannot add
properties dynamically at
run time.
Construct an object
hierarchy by assigning an
object as the prototype
associated with a
constructor function.
Inherit properties by
following the prototype
chain.
Constructor function or
prototype specifies an
initial set of properties. Can
add or remove properties
dynamically to individual
objects or to the entire set
of objects.
50. 50
PublicMembers
All of the class’s attributes and methods are
public and accessible.The public attributes are
created using the this keyword.
There are two main ways of putting members in
a new object:
In the constructor
In the prototype
51. 51
Intheconstructor
This technique is usually used to initialize public instance
variables.The constructor’s this variable is used to add
members to the object.
function Container(param) {
this.member = param;
}
So, if we construct a new object
var myContainer = new Container(„abc‟);
then
myContainer.member contains „abc‟.
52. 52
Intheprototype
This technique is usually used to add public
methods.
To add a method to all objects made by a
constructor, add a function to the constructor’s
prototype:
Container.prototype.stamp = function(string) {
return this.member + string;
}
myContainer.stamp(„def‟); //‟abcdef‟
53. 53
PrivateMembersUsingaNaming
Convention
An underscore is added to the beginning of each
member, signifying that it is intended to be
private.
Using an underscore is a well-known naming
convention; it says that the attribute (or
method) is used internally, and that accessing it
or setting it directly may have unintended
consequences.
54. 54
PrivateMembersThroughClosures
Private members are made by the constructor.
Ordinary vars and parameters of the
constructor becomes the private members.
By convention, we make a private that
parameter.This is used to make the object
available to the private methods.
Private methods cannot be called by public
methods.
56. 56
PrivilegedMembers
A privileged method is able to access the private
variables and methods, and is itself accessible to
public methods and the outside.
58. 58
StaticMembers
Static members operate on the class-level instead
of the instance-level; there is only one copy of each
static member.
These private static members can be accessed from
within the constructor, which means that any
private or privileged function has access to them.
Since they are declared outside of the constructor,
they do not have access to any of the private
attributes, and as such, are not privileged; private
methods can call private static methods, but not the
other way around.
59. 59
var Book = (function() {
var numOfBooks = 0; // Private static attributes.
function checkIsbn(isbn) { // Private static method.
...
}
// Return the constructor.
return function(newIsbn, newTitle, newAuthor) {
var isbn; // Private attributes.
this.getIsbn = function() { // Privileged methods.
return isbn;
};
this.setIsbn = function(newIsbn) {
if(!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
isbn = newIsbn;
};
numOfBooks++; // Keep track of how many Books have been created
this.setIsbn(newIsbn);
}
})();
Book.convertToTitleCase = function(inputString) { // Public static method.
...
};
Book.prototype = { // Public, non-privileged methods.
display: function() {
...
}
};
60. 60
AShortSummary
Private and Privileged members can only be made
when an object is constructed.
Public members can be added at any time.
Having too many privileged methods can cause
memory problems because new copies of all
privileged methods are created for each instance.
In the public members pattern, all methods are
created off of the prototype, which means there is
only one copy of each in memory, no matter how
many instances you create.
64. 64
Howdoesitwork?
Suppose you create the mark object:
var mark = new WorkerBee();
When JavaScript sees the new operator, it creates
a new generic object and passes this new object as
the value of the this keyword to theWorkerBee
constructor function.
Then sets the value of WorkerBee.prototype
to an object of Employee to setup prototype chain.
65. 65
LocalversusInheritedValues
When you access an object property, JavaScript
performs these steps:
1. Check to see if the value exists locally. If it does, return
that value.
2. If there is not a local value, check the prototype chain.
3. If an object in the prototype chain has a value for the
specified property, return that value.
4. If no such property is found, the object does not have
the property.
66. 66
Doesitwork?
Suppose you create amy instance.
var amy = new WorkerBee();
amy.name = “”;
amy.dept = “general”;
amy.projects = [];
Now, suppose you change the value of the name
property in the prototype associated with
Employee.
Employee.prototype.name = “Unknown”;
67. 67
Doesitwork?(cont.)
If you want to have default values for object properties and you want to
be able to change the default values at run time, you should set the
properties in the constructor’s prototype, not in the constructor function
itself.
function Employee() {
this.dept = “general”;
}
Employee.prototype.name = “”;
function WorkerBee() {
this.projects = [];
}
WorkerBee.prototype = new Employee();
amy = new WorkerBee();
Employee.prototype.name = “Unknown”;
68. 68
AddingProperties
In JavaScript, you can add properties to any
object at run time.
To add a property that is specific to a single
object, you assign a value to the object.
mark.bonus = 3000;
Now, the mark object has a bonus property, but
no other WorkerBee has this property.
69. 69
AddingProperties(cont.)
If you add a new property to an object that is
being used as the prototype for a constructor
function, you add that property to all objects
that inherit properties from the prototype.
Employee.prototype.specialty = “none”;
73. ACleanerApproach
Another way of inheriting is by using
the .call/.apply methods. Below are
equivalent:
Using the javascript .call method makes a
cleaner implementation because the ".base"
is not needed anymore.
74. 74
Don’tsupposeitwillwork
Just because you have called the WorkerBee
constructor from inside the Engineering
constructor, you have set up inheritance
appropriately for Engineer object.This is not the
case.
Calling the WorkerBee constructor ensures that
an Engineer object starts out with the properties
specified in all constructor functions that are called.
If you later add properties to the Employee or
WorkerBee prototypes, those properties are not
inherited by the Engineer object.
75. 75
Don’tsupposeitwillwork(cont.)
function Enginner(name, projs, mach) {
WorkerBee.call(this, name, “engineering”, projs);
this.match = mach || “”;
}
var jane = new Engineer(“Doe, Jane”, [“navigator”,
“javascript”], “belau”);
Employee.prototype.specialty = “none”;
The jane object does not inherit the specialty
property.You still need to explicitly set up the
prototype to ensure dynamic inheritance.
76. 76
NoMultipleInheritance
JavaScript does not support multiple
inheritance.
Because an object has a single associated
prototype, JavaScript cannot dynamically inherit
from more than one prototype chain.
In JavaScript, you can have a constructor
function call more than one other constructor
function within it.
77. 77
NoMultipleInheritance(cont.)
function Hobbyist(hobby) {
this.hobby = hobby || “scuba”;
}
function Engineer(name, projs, mach, hobby) {
WorkerBee.call(this, name, “engineering”, projs);
Hobbyist.call(this, hobby);
this.machine = mach || “”;
}
Engineer.prototype = new WorkerBee();
dennis = new Engineer(“Doe Dennis”, [“collabra”], “hugo”);
78. 78
NoMultipleInheritance(cont.)
Assume, you then add a property to the Hobbyist
constructor’s prototype.
Hobbyist.prototype.equipment = [“mask”, “fins”,
“regulator”, “bcd”];
The dennis object does not inherit this new property.
79. 79
PatternsSummary
Public
function Constructor(…) {
this.membername = value;
}
Constructor.prototype.membername = value;
Private
function Constructor(…) {
var that = this;
var membername = value;
function membername(…) {…}
}
80. 80
PatternsSummary(cont.)
Privileged
function Constructor(…) {
this.membername = function(…) {…};
}
Inheritance
var SuperClass = function(…) {
this.superclassmember = value;
};
var SubClass = function(…) {
SuperClass.call(this, params);
this.subclassmember = value;
};
SubClass.prototype = new SuperClass();
82. 82
Practicalclosures
A closure lets you associate some data
(environment) with a function that operates on
that data.
You can use a closure anywhere that you might
normally use an object with only a single
method.
83. 83
Example1:FactoryMethod
Suppose, we wish to add to a page buttons that
adjust the size of the page text.
function size12() {
document.body.style.fontSize = “12px”;
}
function size14() {
document.body.style.fontSize = “14px”;
}
function size16() {
document.body.style.fontSize = “16px”;
}
84. 84
Example1:FactoryMethod(cont.)
Now, one could imagine that you would want to
generalize this notion of an “size function”, and you
would not want to write dozens and dozens of size
functions.
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + “px”;
}
}
var size12 = makeSize(12);
var size14 = makeSize(14);
var size16 = makeSize(16);
86. 86
Example2:Emulatingprivatemethods
withclosures
The shared environment is created in the body
of an anonymous function, which is executed as
soon as it has been defined.
The environment contains two private items: a
variable called privateCounter and a function
called changeBy.
Neither of these private items can be accessed
directly from outside the anonymous function.
90. 90
Explanation
The reason for this is the functions assigned to
onfocus are closures; they consist of the function
definition and the captured environment from the
setupHelp function’s scope.
Three closures have been created, but each one
shares the same single environment.
By the time the onfocus callbacks are executed, the
loop has run its course and the item variable (shared
by all three closures) has been left pointing to the
last entry in the helpText list.
92. UsingAnonymousFunctionstoInduce
theScope
// Iterate through each of the items
for ( var i = 0; i < helpText.length; i++ ) {
// Use a self-executed anonymous function to induce scope
(function(){
// Remember the value within this scope
var item = helpText[i];
// Bind a function to the element
document.getElementById(item).onfocus = function() {
// item refers to a parent variable
// scoped within the context of this for loop
document.getElementById(„help‟).innerHTML = item.help;
};
})();
}
93. 93
Example5:setTimeoutwithFunction
References
A common use for a closure is to provide
parameters for the execution of a function prior to
the execution of that function.
The problem is that the function that passes to
setTimeout cannot provide parameters.
However, code could call another function that
returned a reference to an inner function object,
with that inner function object being passed by
reference to the setTimeout function.The
parameters to be used for the execution of the inner
function are passed with the call to the function that
returns it.
95. Example6:UsingAnonymousFunctionsto
HideVariablesfromtheGlobalScope
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
96. 96
Example7:AssociatingFunctionswith
ObjectInstanceMethods
You want to associate different functions to each
event handler.
Don’t put associateObjWithEvent() inside the
DhtmlObject constructor function. See
Accidental Closures and Performance
considerations for more details.
98. 98
Example8:EncapsulatingRelated
Functionality
The array is going to act as a buffer for the output, but defining it
locally to the function will result in its re-creation on each
execution of the function.
One approach might make the array a global variable so that it
can be re-used without being re-created. But the effect is to
render the code less manageable, as, if it is to be used elsewhere.
It also makes the code less easy to integrate with other code
because it pollutes the global namespace.
A Closure allows the buffer array to be associated (and neatly
packaged) with the function that is dependent upon it and
simultaneously keep the property name to which the buffer array
as assigned out of the global namespace and free of the risk of
name conflicts and accidental interactions.
99. var getImgInPositionedDivHtml = (function(){
var buffAr = [
'<div id="', '', // index 1, DIV ID attribute
'" style="position:absolute;top:', '', // index 3, DIV top position
'px;left:', '', // index 5, DIV left position
'px;width:', '', // index 7, DIV width
'px;height:','', // index 9, DIV height
'px;overflow:hidden;"><img src="', '', // index 11, IMG URL
'" width="', '', // index 13, IMG width
'" height="', '', // index 15, IMG height
'" alt="', '', // index 17, IMG alt text
'"></div>'
];
return function(url, id, width, height, top, left, altText){
buffAr[1] = id; buffAr[3] = top;
buffAr[5] = left;
buffAr[13] = (buffAr[7] = width);
buffAr[15] = (buffAr[9] = height);
buffAr[11] = url; buffAr[17] = altText;
return buffAr.join('');
}; //:End of inner function expression.
})();
100. 100
Example8:EncapsulatingRelated
Functionality
The array is going to act as a buffer for the output, but defining it
locally to the function will result in its re-creation on each
execution of the function.
One approach might make the array a global variable so that it
can be re-used without being re-created. But the effect is to
render the code less manageable. It also makes the code less
easy to integrate with other code because it pollutes the global
namespace.
A Closure allows the buffer array to be associated (and neatly
packaged) with the function that is dependent upon it and
simultaneously keep the property name to which the buffer array
as assigned out of the global namespace and free of the risk of
name conflicts and accidental interactions.
101. AccidentalClosures
Rendering any inner function accessible
outside of the body of the function in which it
was created will form a closure.
Accidentally creating closures can have
harmful side effects as the following section
on the IE memory leak problem describes.
A common situation is where inner functions
are used is as event handlers for DOM
elements.
102. AccidentalClosures(cont.)
var quantaty = 5;
function addGlobalQueryOnClick(linkRef){
if(linkRef){
linkRef.onclick = function(){
this.href += ('?quantaty='+escape(quantaty));
return true;
};
}
}
Whenever the addGlobalQueryOnClick function is called a new inner function is
created (and a closure formed by its assignment).
From the efficiency point of view that would not be significant if the
addGlobalQueryOnClick function was only called once or twice, but if the function
was heavily employed many distinct function objects would be created (one for each
evaluation of the inner function expression).
103. AccidentalClosures(cont.)
As the inner function in the first version is not being used to
exploit the closures produced by its use, it would be more
efficient not to use an inner function, and thus not repeat
the process of creating many essentially identical function
objects.
var quantaty = 5;
function addGlobalQueryOnClick(linkRef){
if(linkRef){
linkRef.onclick = forAddQueryOnClick;
}
}
function forAddQueryOnClick(){
this.href += ('?quantaty='+escape(quantaty));
return true;
}