SlideShare une entreprise Scribd logo
1  sur  103
Télécharger pour lire hors ligne
JavaScript Best Practices
@GregWeng
NCU 2015/10/02
About me
@GregWeng
I'm
Working for Mozilla as a Software Engineer; 2yr+
Responsible for FirefoxOS screen locker (LockScreen)
ECMAScript experience: 6yr+
Free Software and Open Source are important to me
And I'm also a language enthusiast
Like to research programming language themselves
Haskell, Ruby, JavaScript
Java, PHP, Erlang, Python, C/C++
Find me at
Mail: gweng@mozilla.com
IRC: snowmantw
Twitter: @GregWeng
No I don't use Facebook and LINE
The Lesson
Some best practices from our daily work
In this lesson you shall learn how to...
Bind this in Event handlers in the proper way
Deal with object properties w/ constructor & prototype
Extend instantiable object properly
Manage asynchronous flows with Promise
Write your first test case for a pure function
In this lesson you may also try to...
Avoid using closure when it shouldn't appear
Implement functions with closure when it's necessary
Write meaningful comments in JSDoc format
Make your code more expressive with map/forEach
About quizzes and the homework
We will refactor an example from scratch
Quizzes help you to think and learn things
They require you to add comments on several PR pages
Or, raise your hand
If you fail at homework they may save you, too
Homework will be marked strictly according to the public
marking criteria
That means, you either get passed or failed, no other
adjustments except the quizzes
Since I suppose you know this
class is not JavaScript tutorial
Questionnaire
Before the class begins, I would like to ask you if you know:
How to write constructor + prototype (instantiable object)
How to extend an object to add new methods
How to receive and dispatch events
What the 'this' may refer to?
What's a 'closure'?
What's the better way to control asynchronous flow
Let's start from the
embarrassing past...
Some anti-patterns
You put all states in local variables
And then bind events with anonymous callbacks
And then encapsulate them as a 1K+ lines closure
And then try to create a "singleton" via a function that will be
invoked automatically when bootstrapping
And then make it as a Window Manager as Metacity of
Gnome or KWin of KDE
And then you shoot yourself in the foot
Alarm!
Beware of these terms
You put all states in local variables
And then bind events with anonymous callbacks
And then encapsulate them as a 1K+ lines closure
And then try to create a "singleton" via a function that will be
invoked automatically when bootstrapping
And then make it as a Window Manager as Metacity of
Gnome or KWin of KDE
And then you shoot yourself in the foot
class, private, flags, global objects, temporary variables
Usually, bad things happen
when they appear
Example #1
http://bit.
ly/1LeY5lv
"The real badass Todo list"
"You want to write a Todo list,
and you feel it is a simple quest"
"The real badass Todo list"
"So you think, you only need to write several functions"
"The real badass Todo list"
"So you think, you only need to write several functions"
I have three little functions,
one is to draw the list,
one is to fetch the data,
and the last one is to save the data
"The real badass Todo list"
"So you think, you only need to write several functions"
http://bit.ly/1LeY5lv
Quiz#1
(5 minutes)http://bit.ly/1NVdc2y
Things become worse when
the project grows up
Issues
What if TodoItem and TodoInput are written by different
people?
And what will happen if they both write a function called
"draw"?
Name collisions
Since we put all things globally
window
drawList fetchData saveData ...
Names and states may collide
window
drawList fetchData saveData ...
window
drawInput fetchData saveData ...
Working for the List
Working for the Input
En.capsulation
Encapsulation
"Why don't we solve collisions with closure, which is the
most natural mechanism to do that in JavaScript?"
Closure
It's about capture
Closure
It's about capture
http://bit.ly/1LINo9t
Encapsulation by closures
window
drawList fetchData saveData ...
window
drawInput fetchData saveData ...
The "List" closure
The "Input" closure
(insulated)
Example #2
It seems a successful solution to the issues...
Now we have two isolated parts of the program
People can work on that individually
There are no more tangled names and states
To those things like "singletons", closure looks a good
solution to disallow others create the instance twice
It seems a successful solution to the issues...
Now we have two isolated parts of the program
People can work on that individually
There are no more tangled names and states
To those things like "singletons", closure looks a good
solution to disallow others create the instance twice
Really?
Always think about these when you are coding
How do I test the function or instance?
Are these duplicated code necessary?
Could people reuse my code later on?
Is my solution the most expressive one?
Did I express the intention clearly?
Quiz#2
(5 minutes)http://bit.ly/1FCwhF9
Don't be intrigued by closure in such cases
You don't have any references for unit tests
If you really have some re-usable data or functions across
different parts, closures can't use them
That means, it's uneviable to write lots of duplicated
functions do the almost same thing
Don't be intrigued by closure in such cases
You don't have any references for unit tests
If you really have some re-usable data or functions across
different parts, closures can't use them
That means, it's uneviable to write lots of duplicated
functions do the almost same thing
However...
Using closure carefully can still benefit you
"Managers"
"Managers"
"You put all states in an object, and listen to all events and
hope everything will be fine"
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
used by
The only "public" interface
Public interfaces of JavaScript program components
JavaScript components usually use handlers as public
interfaces among the user, server and other components
like to draw or to fire
new events
private helper
methods...
event handlers
server gateway
local data keeper
component
usernative events
server
sync
componentscustom events
So now we have
Managers that can keep queried elements and local data as
their states
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
used by
The only "public" interface
And we're finally able to test our code
Unlike closure, we now have some references the test can
manipulate
About unit test
Right now, you don't need to figure out how it works
Just follow the structure and copy it
Example #3
However, to test them
could be painful soon
The globally "singleton" instance mess up tests
Consider what will happen when we load the files to test
such global object pattern
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
(wrong)
Quiz #3
(5 minutes)http://bit.ly/1FM4KkF
The globally "singleton" instance mess up tests
With such patterns, we need to clear the dummy data and
other states made by previous tests
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
(correct)
_listTodoItem' (null)
*reset it*
The globally "singleton" instance mess up tests
With such patterns, we need to clear the dummy data and
other states made by previous tests
And you barely know how to reset them properly if the
component is 1K+ lines long, and written by lots of people
In Gaia, this has happened countless times
And worse, people sometimes wrote tests rely on that: they
do some changes at the first test, and then use the
contaminated data to perform the next test
"What's the
matter?
I don't write
any test"
Test is good to you because...
There are lots of commits may change your code
Test is good to you because...
There are lots of commits may change your code
People will always screw you and your
code if you don't test them
Test is good to you because...
There are lots of commits may change your code
People will always screw you and your
code if you don't test them
We call these issues regressions
Regressions
To test your code and kill possible regressions
Instantiable Objects
Instantiable objects
TodoListManager
(constructor) start saveData ...onItemAddednew
Test with instantiable objects
Create new instance when new test is performing
unit test for 'saveData'
save some dummy data
TodoListManager
do some tests
_listTodoItem (null)
_listTodoItem' (dummy)
unit test for 'drawList'
do some tests
TodoListManager
_listTodoItem (null)
The pattern
Design a constructor + prototype and then create instances
(constructor)
function
TodoListManager
TodoListManager.prototype
function start()
{...}
function drawList()
{...}
...
Constructor
(constructor)
function
TodoListManager
Is just a function
Constructor
(constructor)
function
TodoListManager
It should set up all data members and do nothing
(constructor)
function TodoListManager() {
this._wrapper = document.query...
this._listTodoItems = []
...
}
!Caveat!
Don't do anything with effects
inside the constructor
Constructor with effects
(constructor)
function
TodoListManager
We prefer to hold the instance before use it
(constructor)
function TodoListManager() {
this._wrapper = document.query...
this._listTodoItems = []
this.fetchData(...);
}
(create the instance & test it)
var instance = new TodoListManager();
// It will do fetching immediately,
// which is BAD
instance.drawList(...)
// Although we only want to test this
Constructor
(constructor)
function
TodoListManager
Put all initial effects in another function
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
...
(create the instance & test it)
var instance = new TodoListManager();
// It will do noththing now
instance.drawList(...)
// We can test this without deal with
// the effect we don't need
It means the shareable methods and data among instances
Prototype
(constructor)
function
TodoListManager(){
this.foo = [];
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
foo: [ ]
start() {}
(new instances)
So it's better to put data ONLY IN SETUP FUNCTIONS
Prototype
(constructor)
function
TodoListManager(){
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
start() {} start() {} start() {} start() {}
(wrong!)
foo: [ ]
foo: [ ]
start() {}
Every test can now modify the instance by their own needs
For tests
(constructor)
function
TodoListManager(){
this.foo = [];
}
TodoListManager.prototype
function start()
{
this.fetchData(...)
}
foo: [1]
start() {}
foo: [ ]
start() {}
foo: [3,2]
start() {}
foo: null
start() {}
foo: {}
start() {}
(new instances)test #1 test #2 test #3 test #4
Example #4
"this"
"this"
the necessary evil to be instantiable
Trolls you when you are not
familiar with it
Quiz#4
5 mins
discuss & search it freely
comment it on the page please
http://bit.ly/1iQdb3V
this
the owner
the window
the bound one
this
the owner
var SomeObject = {
foo: 3,
bar() {
console.log('Foo: ', this.foo);
}
}
SomeObject.bar();
// Will print "Foo:3"
this
the window
var SomeObject = {
foo: 3,
bar() {
console.log('Foo: ', this.foo);
}
}
var bar = SomeObject.bar;
// Will get reference to bar
bar();
// Will print "Foo:undefined"
// without binding and owner,
// the 'this' will become 'window'
this
the bound one
var SomeObject = {
foo: 3,
bar: (function() {
console.log('Foo: ', this.foo);
}).bind(SomeObject)
}
var bar = SomeObject.bar;
// Will get reference to bar
bar();
//
// since it's bound, the this will
// always be 'SomeObject'
You need to bind the 'this' if you use that
It is important since every time you put a callback...
Event handlers should follow the EventListener interface to
make a centralized dispatcher with the bound 'this'
It is important since every time you put a callback...
Event handlers should follow the EventListener interface to
make a centralized dispatcher with the bound 'this'
It is important since every time you put a callback...
Example #4
That's why there are lots of
binding code in the
Using Promise
or face the Callback Hell
I know, I know, it's actually from the Abyss, but the chaos fits the case better better than the order
The
Hell
If you think it's tolerable,
think about this
That's why Promise is so
important
Example #5
new Promise(function(resolve, reject) {
// Do some async things.
// Then resolve it after done.
resolve();
// Or reject it due to the error.
reject();
}).then(function() {
// This function only executes after the
// previous step.
return [1,2,3];
}).then(function() {
// If return another Promise,
// the flow will stop here and only
// continue when the promise is resolved
return new Promise(function(r, c) {
setTimeout(r, 1000);
});
}).then(function() {
// This will not execute within the second
}).catch(function(error) {
// !IMPORTANT!
// Remember to catch Promise error in a
// function like this.
});
The Flow
Promise + Event Handler
|dispatchEvent| as the public interface to send message
|handleEvent| as the public interface to receive message
|Promise| to concat all steps of event handling
TodoListManager
drawList fetchData saveData ...onItemAdded
user event
organized by Promises
The only "public" interface
Promise + Event Handler
|dispatchEvent| as the public interface to send message
|handleEvent| as the public interface to receive message
|Promise| to concat all steps of event handling
handleEvent(event) {
switch(event.type) {
case 'todo-item-created':
var data = event.detail;
this.saveData(data)
.then(this.tidyUp.bind(this))
.then(...)
.then(...)
...
.catch(this.onError.bind(this))
}
}
Promise + Event Handler
Every asynchronous method should return a Promise to
allow we concating it, so we can eliminate all the callbacks
saveData() {
var promise = new Promise(function() {
...
};
return promise;
}
fetchData() {
var promise = new Promise(function() {
...
};
return promise;
}
Conclusion
Solve things in advance but native JavaScript ways
"class" (not ES6 class)
Don't try to copy them
Use "instantiable objects"
prototype + constructor
private
encapsulate
closure Use them very carefully and
wiselyanonymous functions
callback ** PROMISE ** (or beyond)
local variables As immutable as possible
global object Usually it means that you're
doing something really bad
Stop it and re-think the
whole case again
flags, temporary variables
singleton
Homework
1. Fork the Homework repo here
2. Fix all the issues in the code to refactor it
3. After that, make a git branch, commit, and then push it
4. Fire a Pull Request and set review to TAs and me
Remember: you can always ask any question at anytime
Don't struggle with any part you don't really understand
Homework: How to get points
You need at least address all the Tier 1 issues to get 4 points
You will get the extra 3 points from addressing Tier 2 issues
However, you will NOT get any points from the Tier 2,
if you fail to address ANY single issue of Tier 1
You need at least the 4 points from Tier 1 to pass this class
The extra points will benefit you in the following lessons
You can add or remove some code from the example.
However, make sure every change you make is with clear
intentions
Homework: Requirements (Tier 1)
Bind this in Event handlers
Deal with object properties w/ constructor & prototype
Deal with asynchronous flows with Promise
Write your first test case for a pure function (as the last test
of |test-list.js| file shows; for example, to test if |Math.sin|
works well as your assumption)
Homework: Requirements (Tier 2)
Implement functions with closure when it's necessary
Avoid using closure when it shouldn't appear (follow what
we taught in the class)
Write meaningful comments in JSDoc format
(reference: https://en.wikipedia.org/wiki/JSDoc#Example)
Update: people who already commented on PRs
Quiz#1
rockwyc992 : 吳易璋
CaeserNieh : 聶順成
rockwyc992 : 吳易璋
Quiz#2
jason1122g : 邱義傑
bdsword : 蔣彥亭
c910335 : 陳達仁
Davisanity : 林唐正
amm040341 : 蘇聖雅
rueian : 黃瑞安
w181496 : 黃詩凱
Peter654q :莊侑穎
bdsword : 蔣彥亭
Quiz#3
rueian : 黃瑞安
c910335 : 陳達仁
CrashedBboy : 吳承霖
Sharknevercries : 李政遠
jason1122g : 邱義傑
Good work, buddies.

Contenu connexe

Tendances

JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 

Tendances (20)

JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Javascript
JavascriptJavascript
Javascript
 

En vedette

Creative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coinCreative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coinWeb Designers Nepal
 
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jot
Hash Tag Killer - Gamification in customer engagement - Manu Melwin JotHash Tag Killer - Gamification in customer engagement - Manu Melwin Jot
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jotmanumelwin
 
La quaresma i el carnestoltes
La quaresma i el carnestoltesLa quaresma i el carnestoltes
La quaresma i el carnestoltesgvendre3
 
Scribes in Primary Care - Inspiring MDs Productivity
Scribes in Primary Care - Inspiring MDs ProductivityScribes in Primary Care - Inspiring MDs Productivity
Scribes in Primary Care - Inspiring MDs ProductivityErvin Gruia
 
La quaresma i el carnestoltes
La quaresma i el carnestoltesLa quaresma i el carnestoltes
La quaresma i el carnestoltesgvendre3
 
Beckert Dan et al.
Beckert Dan et al.Beckert Dan et al.
Beckert Dan et al.Wettbewerb
 
World Peace Game - Gamification in education - Manu Melwin Joy
World Peace Game - Gamification in education - Manu Melwin JoyWorld Peace Game - Gamification in education - Manu Melwin Joy
World Peace Game - Gamification in education - Manu Melwin Joymanumelwin
 
Advocamp: James Scott
Advocamp: James ScottAdvocamp: James Scott
Advocamp: James ScottInfluitive
 
Change of Pace, Change of Culture- TPPC 2017
Change of Pace, Change of Culture- TPPC 2017Change of Pace, Change of Culture- TPPC 2017
Change of Pace, Change of Culture- TPPC 2017Rachael Arroyo
 
Focus Co Management Session - Dr. Edmison April 2015
Focus Co Management Session - Dr. Edmison April 2015  Focus Co Management Session - Dr. Edmison April 2015
Focus Co Management Session - Dr. Edmison April 2015 FocusEye
 

En vedette (12)

Creative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coinCreative designer and front end developer - Two faces of the same coin
Creative designer and front end developer - Two faces of the same coin
 
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jot
Hash Tag Killer - Gamification in customer engagement - Manu Melwin JotHash Tag Killer - Gamification in customer engagement - Manu Melwin Jot
Hash Tag Killer - Gamification in customer engagement - Manu Melwin Jot
 
La quaresma i el carnestoltes
La quaresma i el carnestoltesLa quaresma i el carnestoltes
La quaresma i el carnestoltes
 
Scribes in Primary Care - Inspiring MDs Productivity
Scribes in Primary Care - Inspiring MDs ProductivityScribes in Primary Care - Inspiring MDs Productivity
Scribes in Primary Care - Inspiring MDs Productivity
 
Matthewtorbitresume
MatthewtorbitresumeMatthewtorbitresume
Matthewtorbitresume
 
La quaresma i el carnestoltes
La quaresma i el carnestoltesLa quaresma i el carnestoltes
La quaresma i el carnestoltes
 
Beckert Dan et al.
Beckert Dan et al.Beckert Dan et al.
Beckert Dan et al.
 
World Peace Game - Gamification in education - Manu Melwin Joy
World Peace Game - Gamification in education - Manu Melwin JoyWorld Peace Game - Gamification in education - Manu Melwin Joy
World Peace Game - Gamification in education - Manu Melwin Joy
 
Advocamp: James Scott
Advocamp: James ScottAdvocamp: James Scott
Advocamp: James Scott
 
Change of Pace, Change of Culture- TPPC 2017
Change of Pace, Change of Culture- TPPC 2017Change of Pace, Change of Culture- TPPC 2017
Change of Pace, Change of Culture- TPPC 2017
 
Focus Co Management Session - Dr. Edmison April 2015
Focus Co Management Session - Dr. Edmison April 2015  Focus Co Management Session - Dr. Edmison April 2015
Focus Co Management Session - Dr. Edmison April 2015
 
Syncope
SyncopeSyncope
Syncope
 

Similaire à JavaScript Best Pratices

The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java ProgrammingKaty Allen
 
Debugging NET Applications With WinDBG
Debugging  NET Applications With WinDBGDebugging  NET Applications With WinDBG
Debugging NET Applications With WinDBGCory Foy
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript TestingScott Becker
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Your java script library
Your java script libraryYour java script library
Your java script libraryjasfog
 
Konstantin Knizhnik: static analysis, a view from aside
Konstantin Knizhnik: static analysis, a view from asideKonstantin Knizhnik: static analysis, a view from aside
Konstantin Knizhnik: static analysis, a view from asidePVS-Studio
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementShiny Zhu
 
Speeding up mobile web apps
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web appsIvano Malavolta
 
Javascript spaghetti stirtrek_5_17
Javascript  spaghetti stirtrek_5_17Javascript  spaghetti stirtrek_5_17
Javascript spaghetti stirtrek_5_17Jared Faris
 

Similaire à JavaScript Best Pratices (20)

All of Javascript
All of JavascriptAll of Javascript
All of Javascript
 
All of javascript
All of javascriptAll of javascript
All of javascript
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Designing A Project Using Java Programming
Designing A Project Using Java ProgrammingDesigning A Project Using Java Programming
Designing A Project Using Java Programming
 
Debugging NET Applications With WinDBG
Debugging  NET Applications With WinDBGDebugging  NET Applications With WinDBG
Debugging NET Applications With WinDBG
 
JS basics
JS basicsJS basics
JS basics
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Agile JavaScript Testing
Agile JavaScript TestingAgile JavaScript Testing
Agile JavaScript Testing
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
Web Development with Smalltalk
Web Development with SmalltalkWeb Development with Smalltalk
Web Development with Smalltalk
 
Your java script library
Your java script libraryYour java script library
Your java script library
 
Grounded Pointers
Grounded PointersGrounded Pointers
Grounded Pointers
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Konstantin Knizhnik: static analysis, a view from aside
Konstantin Knizhnik: static analysis, a view from asideKonstantin Knizhnik: static analysis, a view from aside
Konstantin Knizhnik: static analysis, a view from aside
 
CLR Exception Handing And Memory Management
CLR Exception Handing And Memory ManagementCLR Exception Handing And Memory Management
CLR Exception Handing And Memory Management
 
Speeding up mobile web apps
Speeding up mobile web appsSpeeding up mobile web apps
Speeding up mobile web apps
 
Javascript spaghetti stirtrek_5_17
Javascript  spaghetti stirtrek_5_17Javascript  spaghetti stirtrek_5_17
Javascript spaghetti stirtrek_5_17
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 

Plus de ChengHui Weng

Rust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemRust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemChengHui Weng
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS EngineChengHui Weng
 
Gatekeeper: API gateway
Gatekeeper: API gatewayGatekeeper: API gateway
Gatekeeper: API gatewayChengHui Weng
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkeyChengHui Weng
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP IntroductionChengHui Weng
 
Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)ChengHui Weng
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notChengHui Weng
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 

Plus de ChengHui Weng (8)

Rust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystemRust + python: lessons learnt from building a toy filesystem
Rust + python: lessons learnt from building a toy filesystem
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
 
Gatekeeper: API gateway
Gatekeeper: API gatewayGatekeeper: API gateway
Gatekeeper: API gateway
 
Catch a spider monkey
Catch a spider monkeyCatch a spider monkey
Catch a spider monkey
 
Yampa AFRP Introduction
Yampa AFRP IntroductionYampa AFRP Introduction
Yampa AFRP Introduction
 
Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)Introduction to Basic Haskell Components (In Chinese)
Introduction to Basic Haskell Components (In Chinese)
 
JSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why notJSDC 2014 - functional java script, why or why not
JSDC 2014 - functional java script, why or why not
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 

Dernier

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Dernier (20)

Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

JavaScript Best Pratices

  • 3. I'm Working for Mozilla as a Software Engineer; 2yr+ Responsible for FirefoxOS screen locker (LockScreen) ECMAScript experience: 6yr+ Free Software and Open Source are important to me And I'm also a language enthusiast Like to research programming language themselves Haskell, Ruby, JavaScript Java, PHP, Erlang, Python, C/C++
  • 4. Find me at Mail: gweng@mozilla.com IRC: snowmantw Twitter: @GregWeng
  • 5. No I don't use Facebook and LINE
  • 6. The Lesson Some best practices from our daily work
  • 7. In this lesson you shall learn how to... Bind this in Event handlers in the proper way Deal with object properties w/ constructor & prototype Extend instantiable object properly Manage asynchronous flows with Promise Write your first test case for a pure function
  • 8. In this lesson you may also try to... Avoid using closure when it shouldn't appear Implement functions with closure when it's necessary Write meaningful comments in JSDoc format Make your code more expressive with map/forEach
  • 9. About quizzes and the homework We will refactor an example from scratch Quizzes help you to think and learn things They require you to add comments on several PR pages Or, raise your hand If you fail at homework they may save you, too Homework will be marked strictly according to the public marking criteria That means, you either get passed or failed, no other adjustments except the quizzes
  • 10. Since I suppose you know this class is not JavaScript tutorial
  • 11. Questionnaire Before the class begins, I would like to ask you if you know: How to write constructor + prototype (instantiable object) How to extend an object to add new methods How to receive and dispatch events What the 'this' may refer to? What's a 'closure'? What's the better way to control asynchronous flow
  • 12. Let's start from the embarrassing past...
  • 13.
  • 14.
  • 15. Some anti-patterns You put all states in local variables And then bind events with anonymous callbacks And then encapsulate them as a 1K+ lines closure And then try to create a "singleton" via a function that will be invoked automatically when bootstrapping And then make it as a Window Manager as Metacity of Gnome or KWin of KDE And then you shoot yourself in the foot
  • 17. Beware of these terms You put all states in local variables And then bind events with anonymous callbacks And then encapsulate them as a 1K+ lines closure And then try to create a "singleton" via a function that will be invoked automatically when bootstrapping And then make it as a Window Manager as Metacity of Gnome or KWin of KDE And then you shoot yourself in the foot class, private, flags, global objects, temporary variables
  • 18. Usually, bad things happen when they appear
  • 20. "The real badass Todo list" "You want to write a Todo list, and you feel it is a simple quest"
  • 21. "The real badass Todo list" "So you think, you only need to write several functions"
  • 22. "The real badass Todo list" "So you think, you only need to write several functions" I have three little functions, one is to draw the list, one is to fetch the data, and the last one is to save the data
  • 23. "The real badass Todo list" "So you think, you only need to write several functions" http://bit.ly/1LeY5lv
  • 25. Things become worse when the project grows up
  • 26. Issues What if TodoItem and TodoInput are written by different people? And what will happen if they both write a function called "draw"?
  • 28. Since we put all things globally window drawList fetchData saveData ...
  • 29. Names and states may collide window drawList fetchData saveData ... window drawInput fetchData saveData ... Working for the List Working for the Input
  • 31. Encapsulation "Why don't we solve collisions with closure, which is the most natural mechanism to do that in JavaScript?"
  • 34. Encapsulation by closures window drawList fetchData saveData ... window drawInput fetchData saveData ... The "List" closure The "Input" closure (insulated)
  • 36. It seems a successful solution to the issues... Now we have two isolated parts of the program People can work on that individually There are no more tangled names and states To those things like "singletons", closure looks a good solution to disallow others create the instance twice
  • 37. It seems a successful solution to the issues... Now we have two isolated parts of the program People can work on that individually There are no more tangled names and states To those things like "singletons", closure looks a good solution to disallow others create the instance twice Really?
  • 38. Always think about these when you are coding How do I test the function or instance? Are these duplicated code necessary? Could people reuse my code later on? Is my solution the most expressive one? Did I express the intention clearly?
  • 40. Don't be intrigued by closure in such cases You don't have any references for unit tests If you really have some re-usable data or functions across different parts, closures can't use them That means, it's uneviable to write lots of duplicated functions do the almost same thing
  • 41. Don't be intrigued by closure in such cases You don't have any references for unit tests If you really have some re-usable data or functions across different parts, closures can't use them That means, it's uneviable to write lots of duplicated functions do the almost same thing However...
  • 42. Using closure carefully can still benefit you
  • 44. "Managers" "You put all states in an object, and listen to all events and hope everything will be fine" TodoListManager drawList fetchData saveData ...onItemAdded user event used by The only "public" interface
  • 45. Public interfaces of JavaScript program components JavaScript components usually use handlers as public interfaces among the user, server and other components like to draw or to fire new events private helper methods... event handlers server gateway local data keeper component usernative events server sync componentscustom events
  • 46. So now we have Managers that can keep queried elements and local data as their states TodoListManager drawList fetchData saveData ...onItemAdded user event used by The only "public" interface
  • 47. And we're finally able to test our code Unlike closure, we now have some references the test can manipulate
  • 48. About unit test Right now, you don't need to figure out how it works Just follow the structure and copy it
  • 50. However, to test them could be painful soon
  • 51. The globally "singleton" instance mess up tests Consider what will happen when we load the files to test such global object pattern unit test for 'saveData' save some dummy data TodoListManager do some tests _listTodoItem (null) _listTodoItem' (dummy) unit test for 'drawList' do some tests (wrong)
  • 53. The globally "singleton" instance mess up tests With such patterns, we need to clear the dummy data and other states made by previous tests unit test for 'saveData' save some dummy data TodoListManager do some tests _listTodoItem (null) _listTodoItem' (dummy) unit test for 'drawList' do some tests (correct) _listTodoItem' (null) *reset it*
  • 54. The globally "singleton" instance mess up tests With such patterns, we need to clear the dummy data and other states made by previous tests And you barely know how to reset them properly if the component is 1K+ lines long, and written by lots of people In Gaia, this has happened countless times And worse, people sometimes wrote tests rely on that: they do some changes at the first test, and then use the contaminated data to perform the next test
  • 55. "What's the matter? I don't write any test"
  • 56. Test is good to you because... There are lots of commits may change your code
  • 57. Test is good to you because... There are lots of commits may change your code People will always screw you and your code if you don't test them
  • 58. Test is good to you because... There are lots of commits may change your code People will always screw you and your code if you don't test them We call these issues regressions
  • 60. To test your code and kill possible regressions Instantiable Objects
  • 62. Test with instantiable objects Create new instance when new test is performing unit test for 'saveData' save some dummy data TodoListManager do some tests _listTodoItem (null) _listTodoItem' (dummy) unit test for 'drawList' do some tests TodoListManager _listTodoItem (null)
  • 63. The pattern Design a constructor + prototype and then create instances (constructor) function TodoListManager TodoListManager.prototype function start() {...} function drawList() {...} ...
  • 65. Constructor (constructor) function TodoListManager It should set up all data members and do nothing (constructor) function TodoListManager() { this._wrapper = document.query... this._listTodoItems = [] ... }
  • 67. Don't do anything with effects inside the constructor
  • 68. Constructor with effects (constructor) function TodoListManager We prefer to hold the instance before use it (constructor) function TodoListManager() { this._wrapper = document.query... this._listTodoItems = [] this.fetchData(...); } (create the instance & test it) var instance = new TodoListManager(); // It will do fetching immediately, // which is BAD instance.drawList(...) // Although we only want to test this
  • 69. Constructor (constructor) function TodoListManager Put all initial effects in another function TodoListManager.prototype function start() { this.fetchData(...) } ... (create the instance & test it) var instance = new TodoListManager(); // It will do noththing now instance.drawList(...) // We can test this without deal with // the effect we don't need
  • 70. It means the shareable methods and data among instances Prototype (constructor) function TodoListManager(){ this.foo = []; } TodoListManager.prototype function start() { this.fetchData(...) } foo: [ ] start() {} foo: [ ] start() {} foo: [ ] start() {} foo: [ ] start() {} foo: [ ] start() {} (new instances)
  • 71. So it's better to put data ONLY IN SETUP FUNCTIONS Prototype (constructor) function TodoListManager(){ } TodoListManager.prototype function start() { this.fetchData(...) } start() {} start() {} start() {} start() {} (wrong!) foo: [ ] foo: [ ] start() {}
  • 72. Every test can now modify the instance by their own needs For tests (constructor) function TodoListManager(){ this.foo = []; } TodoListManager.prototype function start() { this.fetchData(...) } foo: [1] start() {} foo: [ ] start() {} foo: [3,2] start() {} foo: null start() {} foo: {} start() {} (new instances)test #1 test #2 test #3 test #4
  • 75. "this" the necessary evil to be instantiable
  • 76. Trolls you when you are not familiar with it
  • 77. Quiz#4 5 mins discuss & search it freely comment it on the page please http://bit.ly/1iQdb3V
  • 79. this the owner var SomeObject = { foo: 3, bar() { console.log('Foo: ', this.foo); } } SomeObject.bar(); // Will print "Foo:3"
  • 80. this the window var SomeObject = { foo: 3, bar() { console.log('Foo: ', this.foo); } } var bar = SomeObject.bar; // Will get reference to bar bar(); // Will print "Foo:undefined" // without binding and owner, // the 'this' will become 'window'
  • 81. this the bound one var SomeObject = { foo: 3, bar: (function() { console.log('Foo: ', this.foo); }).bind(SomeObject) } var bar = SomeObject.bar; // Will get reference to bar bar(); // // since it's bound, the this will // always be 'SomeObject'
  • 82. You need to bind the 'this' if you use that It is important since every time you put a callback...
  • 83. Event handlers should follow the EventListener interface to make a centralized dispatcher with the bound 'this' It is important since every time you put a callback...
  • 84. Event handlers should follow the EventListener interface to make a centralized dispatcher with the bound 'this' It is important since every time you put a callback...
  • 85. Example #4 That's why there are lots of binding code in the
  • 87. or face the Callback Hell I know, I know, it's actually from the Abyss, but the chaos fits the case better better than the order
  • 89. If you think it's tolerable, think about this
  • 90.
  • 91. That's why Promise is so important
  • 93. new Promise(function(resolve, reject) { // Do some async things. // Then resolve it after done. resolve(); // Or reject it due to the error. reject(); }).then(function() { // This function only executes after the // previous step. return [1,2,3]; }).then(function() { // If return another Promise, // the flow will stop here and only // continue when the promise is resolved return new Promise(function(r, c) { setTimeout(r, 1000); }); }).then(function() { // This will not execute within the second }).catch(function(error) { // !IMPORTANT! // Remember to catch Promise error in a // function like this. }); The Flow
  • 94. Promise + Event Handler |dispatchEvent| as the public interface to send message |handleEvent| as the public interface to receive message |Promise| to concat all steps of event handling TodoListManager drawList fetchData saveData ...onItemAdded user event organized by Promises The only "public" interface
  • 95. Promise + Event Handler |dispatchEvent| as the public interface to send message |handleEvent| as the public interface to receive message |Promise| to concat all steps of event handling handleEvent(event) { switch(event.type) { case 'todo-item-created': var data = event.detail; this.saveData(data) .then(this.tidyUp.bind(this)) .then(...) .then(...) ... .catch(this.onError.bind(this)) } }
  • 96. Promise + Event Handler Every asynchronous method should return a Promise to allow we concating it, so we can eliminate all the callbacks saveData() { var promise = new Promise(function() { ... }; return promise; } fetchData() { var promise = new Promise(function() { ... }; return promise; }
  • 98. Solve things in advance but native JavaScript ways "class" (not ES6 class) Don't try to copy them Use "instantiable objects" prototype + constructor private encapsulate closure Use them very carefully and wiselyanonymous functions callback ** PROMISE ** (or beyond) local variables As immutable as possible global object Usually it means that you're doing something really bad Stop it and re-think the whole case again flags, temporary variables singleton
  • 99. Homework 1. Fork the Homework repo here 2. Fix all the issues in the code to refactor it 3. After that, make a git branch, commit, and then push it 4. Fire a Pull Request and set review to TAs and me Remember: you can always ask any question at anytime Don't struggle with any part you don't really understand
  • 100. Homework: How to get points You need at least address all the Tier 1 issues to get 4 points You will get the extra 3 points from addressing Tier 2 issues However, you will NOT get any points from the Tier 2, if you fail to address ANY single issue of Tier 1 You need at least the 4 points from Tier 1 to pass this class The extra points will benefit you in the following lessons You can add or remove some code from the example. However, make sure every change you make is with clear intentions
  • 101. Homework: Requirements (Tier 1) Bind this in Event handlers Deal with object properties w/ constructor & prototype Deal with asynchronous flows with Promise Write your first test case for a pure function (as the last test of |test-list.js| file shows; for example, to test if |Math.sin| works well as your assumption)
  • 102. Homework: Requirements (Tier 2) Implement functions with closure when it's necessary Avoid using closure when it shouldn't appear (follow what we taught in the class) Write meaningful comments in JSDoc format (reference: https://en.wikipedia.org/wiki/JSDoc#Example)
  • 103. Update: people who already commented on PRs Quiz#1 rockwyc992 : 吳易璋 CaeserNieh : 聶順成 rockwyc992 : 吳易璋 Quiz#2 jason1122g : 邱義傑 bdsword : 蔣彥亭 c910335 : 陳達仁 Davisanity : 林唐正 amm040341 : 蘇聖雅 rueian : 黃瑞安 w181496 : 黃詩凱 Peter654q :莊侑穎 bdsword : 蔣彥亭 Quiz#3 rueian : 黃瑞安 c910335 : 陳達仁 CrashedBboy : 吳承霖 Sharknevercries : 李政遠 jason1122g : 邱義傑 Good work, buddies.