CSE 331Software Design & Implementation
Hal PerkinsSpring 2019JavaScript II
UW CSE 331 Spring 2019 1
The plan
• So far:– JavaScript language basics– Running JS code in browsers
• Now:– JS objects with methods– Prototypes and classes– Very basic user interface concepts
• For hw8 and hw9, we will use the react library which has similar UI ideas but different details
UW CSE 331 Spring 2019 2
JS Functions (review)
• A function is a value– It can be declared and named in the “usual” way:
function average(x, y) {return (x + y) / 2
}– Or it can be an anonymous function value written
with => notation and the value can be assigned to a variable or used as a parameterlet avg = (x, y) => (x + y) / 2
UW CSE 331 Spring 2019 3
JS Data objects (review)
• An object is a collection of named fields and values (properties)
let mouse = {name:“mickey”, age:90}• Properties are referenced with [] or . notation; fields
can be changed, added, deleted:mouse.home = “california”mouse[“studio”] = “Disney”delete mouse.age
UW CSE 331 Spring 2019 4
Objects with methods
• Properties in a JavaScript object can include methods (functions) – just like in Java
let account = {owner = “Gandalf”,balance = 10000,deposit: function(amount) {this.balance += amount
}}
• We call methods in the expected way:account.deposit(100)
UW CSE 331 Spring 2019 5
Objects with methods
• There is a bit of shorthand available. Instead oflet account = {
…deposit: function(amount) {
this.balance += amount}
}we can write
let account = {…deposit(amount) {
this.balance += amount}
}but the meaning is exactly the same
UW CSE 331 Spring 2019 6
Creating new objects
• JavaScript has an unconventional model: it is an object-oriented language, but there are no classes!– But everything is an object, including functions(!)
• Instead, we create new objects by returning them as values of functions– There are also various ways of creating related
collections of objects using prototypes – we’ll get to that in a bit
UW CSE 331 Spring 2019 7
Creating objects with factory functions
• Write a function to create and return new objectsfunction createAccount(owner, balance) {
return {owner,balance,deposit: function(amount) {
this.balance += amount}
}}
• Then we can create a new account like this:account = createAccount(“Gandalf”, 10000)
UW CSE 331 Spring 2019 8
Prototypes
• In the previous example, every new Account object has its own deposit property, even though this is duplicated in all accounts. We would like to share a single copy for all accounts.
• Prototypes to the rescue! Every JavaScript object is linked behind the scenes to a prototype object from which it inherits properties– Idea: use prototypes to collect properties that are
common to multiple objects– Default prototype is Object.prototype, but we
can specify a different prototype object when we create a new object
UW CSE 331 Spring 2019 9
Prototype for new accounts
• For our account objects, we want a prototype object containing the common deposit function
const accountPrototype = {deposit: function(amount) {
this.balance += amount}
}
UW CSE 331 Spring 2019 10
New account with prototypes
• Once we have the prototype, we use Object.create to get a new object that has the given prototype, then add other properties to the object as needed:
function createAccount(owner, balance) {const result =
Object.create(accountPrototype)result.owner = ownerresult.balance = balance;return result
}
UW CSE 331 Spring 2019 11
Constructors and new
• There is a special way to write and invoke object-creating factory functions using new
• In JavaScript all functions are actually objects, so they can have properties. A function’s prototypeproperty is used when a function is called with new.
• Execution of new factoryFunction:1. Create a new object whose prototype is
factoryFunction.prototype2. this is bound to the newly created object3. the body of the function is invoked4. the new operator yields the created object
UW CSE 331 Spring 2019 12
“Constructor” for new Accounts
• Here is a factory function for our account objectsfunction Account(owner, balance) {this.owner = ownerthis.balance = balance
}– By convention we name the factory function as we
would a class constructor in a language like Java• We add method(s) to the function’s prototype to be
used when it is called with new:Account.prototype.deposit =function(amount) {this.balance += amount
}
UW CSE 331 Spring 2019 13
And now the “new” magic!
• Given Account function with its prototype property initialized as above, a client program can call
let account = new Account(‘Gandalf’, 10000)
– What happens????• The Account function creates a new object• The this parameter points to the new object• The body of the Account function serves as a
constructor and sets object properties• Lastly the new operator sets the object’s prototype
to Account.prototype and things in the prototype are inherited as “part” of the object
Yikes!!!!UW CSE 331 Spring 2019 14
So where are we?
• We now have a way of creating functions that act like Java constructors when used as the operand of new
• But we don’t have classes!– Or do we?
• We don’t, but we do have the ability to create sets of objects that behave like instances of a common class and share common properties
UW CSE 331 Spring 2019 15
ES6 to the rescue! Classes!! (not really!)
• ECMAScript 6 added syntax for classes. For our running example we can now write
class Account {constructor(owner, balance) {this.owner = ownerthis.balance = balance
}deposit(amount) {this.balance += amount
}}
UW CSE 331 Spring 2019 16
But there’s nothing new!!
• This syntax does exactly the same thing as the previous code:– We still create new objects with
let account = new Account(‘Gandalf’, 10000)
– The deposit method is still part of the Account.prototype as before
• By all means use this new class syntax (and we’ll use it for the react user interface code in hw8/hw9)– But realize that it is not the same as in Java – it’s a
constructor function whose prototype has methods– There are still no actual classes in JavaScript
UW CSE 331 Spring 2019 17
Time to take a deep breath!
UW CSE 331 Spring 2019 18
A bit on user interfaces and callbacks
• To have interactive web pages we need– UI elements like buttons, text boxes, and more– A way of associating code to be executed with the
UI elements• A simple solution is to specify the code to be
executed directly in the html text that creates the UI elements on the page– The code can either be given in the html, or can
be calls to JavaScript functions– Demo: ui-example.html and ui-example.js
UW CSE 331 Spring 2019 19
UI handling – events and callbacks
• In general we want flexibility in UI handling– Potentially multiple things to do when a button is
clicked or a field filled in– Would like to decouple UI elements from the code
that handles them as much as possible• Standard pattern for this (and more to come in the
next lecture): observer/observable or listener pattern• Idea: UI elements generate events when something
interesting happens: mouse click, keyboard, touch screen, etc.
• We register code (functions) that will get called when a UI event happens
UW CSE 331 Spring 2019 20
UI listeners
• General strategy to handle user events1. Create UI controls (widgets) like buttons, text
fields, drawing windows2. Write UI code to be executed when events we’re
interested in occur3. Register “listeners” (functions) with the UI
widgets. Each widget keeps a list of listeners (functions) that are registered with it.
4. When an event occurs, the specific widget notifies all of its registered listeners by calling the designated function
UW CSE 331 Spring 2019 21
Example
• See events.html / events.js
• Note: although we don’t do it in this example, a UI widget can have multiple listeners and it will notify each of them when something happens. Each listener can decide what it wants to do in response to the event, if anything.
UW CSE 331 Spring 2019 22
Still to come
• Sections!!!– Be there tomorrow– Content is hw8, overview of react, tour of the hw8
starter code, additional JavaScript as needed, etc.
• HW8 should be posted tonight and starter code (there’s a bunch of framework code provided for you) pushed to repos tomorrow
UW CSE 331 Spring 2019 23