Разделы презентаций


Module 5: JavaScript in Browser D. Petin 07/2014

AgendaJS in BrowserEvents MemoryClosure[1][2][3][4]

Слайды и текст этой презентации

Слайд 1Module 5: JavaScript in Browser

D. Petin

07/2014

Module 5:  JavaScript in BrowserD. Petin07/2014

Слайд 2Agenda
JS in Browser
Events
Memory
Closure


[1]
[2]
[3]
[4]

AgendaJS in BrowserEvents MemoryClosure[1][2][3][4]

Слайд 3
JavaScript in Browser

JavaScript in Browser

Слайд 4JavaScript in Browser
BOM
window
DOM

JavaScript in BrowserBOMwindowDOM

Слайд 5
Events

Events

Слайд 6Description
How JavaScript communicates with the world?

In outline this mechanism works

by next scenario: user does something and this action is

an event for browser. JavaScript observes pages in the browser. And if event has occurred, script will be activated.

[1]

DescriptionHow JavaScript communicates with the world?In outline this mechanism works by next scenario: user does something and

Слайд 7Event handling
But JavaScript doesn't observe events by default. You should

specify to your code what events are interesting for it.

There

are 3 basic ways to subscribe to an event:
- inline in HTML
- using of onevent attribute
using special methods

First and second ways are deprecated for present days. Let's take a look at event handling in more details.

[1]

[2]

Event handlingBut JavaScript doesn't observe events by default. You should specify to your code what events are

Слайд 8Inline handling
Imagine that we have some HTML-element, for example

and we want to do some action when user clicks

the button.


First way: inline adding of JavaScript into HTML. If we use this technique, we should update HTML-page and set some JS code in onevent attribute of HTML-element.

Never use this way, because it influences HTML and JavaScript simultaneously. So let's look at the next option!

[1]

[2]

Inline handlingImagine that we have some HTML-element, for example and we want to do some action when

Слайд 9Using of onevent attribute
btn.onclick = action;
The next way doesn't

touch HTML. For adding event handler you need to find

an object that is a JavaScript model of HTML-element.

For example, your button has id btn:


Where action is some function
defined as function action () { . . . }

Then desired object will be created automatically. Next you can use an onclick property:

[1]

[2]

Using of onevent attribute btn.onclick = action;The next way doesn't touch HTML. For adding event handler you

Слайд 10Proper ways
Previous way makes sense, but has some limitations. For

example you can not use more than one handler for

one event, because you set a function on onevent attribute directly.

btn.addEventListener(“click”, action, false);

But this method doesn't work in IE. For IE you should use:

Next method helps solve this and some other problems:

btn.attachEvent(“onclick”, action);

[1]

[2]

Proper waysPrevious way makes sense, but has some limitations. For example you can not use more than

Слайд 11Proper ways
btn.removeEventListener(“click”, action);
In IE:
Also, you can unsubscribe from

any event. In W3C:
btn.detachEvent(“onclick”, action);
Interesting note
Why we refer

to W3C if JavaScript syntax is specified by ECMA? Because ECMA specifies only cross-platform part of language and does not describes any API. The browser API is determined by W3C standards. It applies to events, DOM, storages, etc.

[1]

[1]

Proper waysbtn.removeEventListener(“click”, action);  In IE:Also, you can unsubscribe from any event. In W3C:btn.detachEvent(“onclick”, action);  Interesting

Слайд 12Bubbling and Capturing
The third parameter of addEventListener is a phase

of event processing. There are 2 phases:
bubbling (if parameter

is ‘false’)
capturing (if parameter is ‘true’).

W3C browsers supports both phases whereas in IE only bubbling is supported.








For example:
There are three nested elements like , and (

or something else). When event has occurred inside the element its processing starts from top of DOM - window and moves to the target element. After being processed in target element event will go back.

[1]

Bubbling and CapturingThe third parameter of addEventListener is a phase of event processing. There are 2 phases:

Слайд 13Bubbling and Capturing
Bubbling
Capturing


/>




[1]
[2]
[3]

Bubbling and CapturingBubblingCapturing         [1][2][3]

Слайд 14Event object
For every event in the browser instance of Event

object will be created.

You can take it if you

need. In W3C browsers this object will be passed as a first parameter of event handler:

btn.addEventListener(“click”, action, false);

Where action was defined as:

function action (e) { . . . }

[1]

Event objectFor every event in the browser instance of Event object will be created. You can take

Слайд 15Event object
Event object is supported in IE, too, but it’s

located in object window and its name is event:
var e

= window.event;

You have a possibility to use a cross-browser solution.:

function action (e) {
e = e || window.event;
. . .
}

[1]

[2]

Event objectEvent object is supported in IE, too, but it’s located in object window and its name

Слайд 16Control of Default behavior
Sometimes a default scenario of event processing

includes some additional behavior: bubbling and capturing or displaying context

menu.

If you don't need a default behavior, you can cancel it. Use object event and next methods for this purpose:

e.preventDefault();

e.stopPropagation();

for discarding bubbling and capturing.

for aborting default browser behavior.
.

[1]

[2]

Control of Default behaviorSometimes a default scenario of event processing includes some additional behavior: bubbling and capturing

Слайд 17
Memory and Sandbox

Memory and Sandbox

Слайд 18Basic info
Free space in browser sandbox is allocated for each

variable in JavaScript.

Sandbox is a special part of memory that

will be managed by browser: JavaScript takes simplified and secure access to "memory“, browser translates JS commands and does all low-level work.

As a result memory, PC and user data has protection from downloaded JavaScript malware.
Basic infoFree space in browser sandbox is allocated for each variable in JavaScript.Sandbox is a special part

Слайд 19Scope
The scope is a special JavaScript object which was created

by browser in the sandbox and used for storing variables.

Each

function in JavaScript has its own personal scope. Scope is formed when a function is called and destroyed after the function finishes.

This behavior helps to manage local variables mechanism.

window object is a top-level scope for all default and global variables.

ScopeThe scope is a special JavaScript object which was created by browser in the sandbox and used

Слайд 20Scope
window_scope = {
test: function,
a:

10,
b: 20
};
test_scope = {
b:

40
};

[1]

[2]

[3]

[41

var a = 10;
test();
function test () {
a = 30;
var b = 40;
}
var b = 20;
console.log(a, b);

Scopewindow_scope = {   test: function,   a: 10,   b: 20};test_scope = {

Слайд 21Value-types and Reference-types
Unfortunately some objects are too large for scope.

For example string or function. There is simple division into

value-types and reference-types for this reason.

Value-types are stored in scope completely and for reference-types only reference to their location is put in scope. They themselves are located in place called "memory heap".

String and all Objects are reference-types. Other data types are stored in scope.
Value-types and Reference-typesUnfortunately some objects are too large for scope. For example string or function. There is

Слайд 22Memory cleaning
The basic idea of memory cleaning: when function is

finished, scope should be destroyed and as a result all

local variables should be destroyed.

This will work for value-types.

As for reference-types: deleting the scope destroys only reference. The object in heap itself will be destroyed only when it becomes unreachable.
Memory cleaningThe basic idea of memory cleaning: when function is finished, scope should be destroyed and as

Слайд 23Unreachable links
An object is considered unreachable if it is not

referenced from the client area of code.

Garbage collector is responsible

for the cleanup of unreachable objects.

It's a special utility that will launch automatically if there isn’t enough space in the sandbox.

If an object has at least one reference it is still reachable and will survive after memory cleaning.
Unreachable linksAn object is considered unreachable if it is not referenced from the client area of code.Garbage

Слайд 24Unreachable links
action_scope = {
a: reference,

b: reference
};
… somewhere in heap …
function action () {

var a = new Point(10, 20),
b = new Point(15, 50);
}

{x: 10, y: 20}

{x: 15, y: 50}

[1]

[2]

[3]

Unreachable linksaction_scope = {   a: reference,   b: reference};… somewhere in heap …function action

Слайд 25
Closures

Closures

Слайд 26Closure
FYI: if scope is an object and it is not

deleted it is still reachable, isn't it?

Absolutely! This mechanism is

called closure.

If you save at least one reference to scope, all its content will survive after function finishing.
ClosureFYI: if scope is an object and it is not deleted it is still reachable, isn't it?Absolutely!

Слайд 27Example
function getPi () {
var value = 3.14;

return function () {

return value; };
}

var pi = getPi();
. . .
L = 2*pi()*R;

[1]

[3]

[2]

Examplefunction getPi () {  var value = 3.14;  return function () {

Обратная связь

Если не удалось найти и скачать доклад-презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое TheSlide.ru?

Это сайт презентации, докладов, проектов в PowerPoint. Здесь удобно  хранить и делиться своими презентациями с другими пользователями.


Для правообладателей

Яндекс.Метрика