程序代写 JavaScript:

JavaScript:
Prototypes, DOM and Events
Computer Science and Engineering  College of Engineering  The Ohio State University

Copyright By PowCoder代写 加微信 powcoder

Prototypes
Every object has a prototype
A hidden, indirect property ([[Prototype]])
Computer Science and Engineering  The Ohio State University
What is a prototype?
Just another object! Like any other!
When accessing a property (i.e. obj.p)
First look for p in obj
If not found, look for p in obj’s prototype If not found, look for p in that object’s prototype!
And so on, until reaching the basic system object

Prototype Chaining
Computer Science and Engineering  The Ohio State University
greeting doors pi
toString hasOwnProperty
true false

Class-Based Inheritance
Computer Science and Engineering  The Ohio State University
interfaces
extends implements
instantiates

Consider two objects
Computer Science and Engineering  The Ohio State University
var dog = {name: “Rex”, age: 3};
var pet = {color: “blue”};
Assume pet is dog’s prototype
// dog.name is “Rex”
// dog.color is “blue” (follow chain) pet.color = “brown”;
// dog.color is “brown” (prop changed) dog.color = “green”;
// pet.color is still “brown” (hiding)

Delegation to Prototype
Computer Science and Engineering  The Ohio State University
name “Rex”
color “brown”

Prototypes Are Dynamic Too
Computer Science and Engineering  The Ohio State University
Prototypes can add/remove properties Changes are felt by all children
// dog is {name: “Rex”, age: 3}
// dog.mood & pet.mood are undefined pet.mood = “happy”; // add to pet // dog.mood is now “happy” too pet.bark = function() {
return this.name + ” is ” + this.mood;
dog.bark(); //=> “Rex is happy” pet.bark(); //=> “undefined is happy”

Delegation to Prototype
Computer Science and Engineering  The Ohio State University
dog.bark();
pet.bark();
name “Rex” age 3
color “brown” mood “happy”
return this.name
+ this.mood;

Connecting Objects & Prototypes
Computer Science and Engineering  The Ohio State University
How does an object get a prototype?
var c = new Circle();
1. Every function has a prototype property
Do not confuse with hidden [[Prototype]]! 2. Object’s prototype link—[[Prototype]]—
is set to the function’s prototype property When a function Foo is used as a constructor, i.e. new Foo(), the value of Foo’s prototype property is the prototype object of the created object

Prototypes And Constructors
Computer Science and Engineering  The Ohio State University
area constructor
this.centerX =x;
this.centerY =y;
… Etc …

Prototypes And Constructors
Computer Science and Engineering  The Ohio State University
c = new Circle()
area constructor
this.centerX =x;
this.centerY =y;
… Etc …

Prototypes And Constructors
Computer Science and Engineering  The Ohio State University
c = new Circle()
area constructor
this.centerX =x;
this.centerY =y;
… Etc …

Prototypes And Constructors
c = new Circle()
centerX centerY radius
Computer Science and Engineering  The Ohio State University
area constructor
this.centerX =x;
this.centerY =y;
… Etc …

Idiom: Methods in Prototype
function Dog(n, a) {
this.name = n;
this.age = a;
var canine = {
bark: function (sound) {
return this.name + “says” + sound;
Dog.prototype = canine;
Computer Science and Engineering  The Ohio State University

Idiom: Methods in Prototype
function Dog(n, a) {
this.name = n;
this.age = a;
var canine = {
bark: function (sound) {
return this.name + “says” + sound;
Dog.prototype = canine;
Computer Science and Engineering  The Ohio State University

Idiom: Methods in Prototype
function Dog(n, a) {
this.name = n;
this.age = a;
Dog.prototype = {
bark: function (sound) {
return this.name + “says” + sound;
// set prototype to new anonymous object
Computer Science and Engineering  The Ohio State University

Idiom: Methods in Prototype
function Dog(n, a) {
this.name = n;
this.age = a;
Dog.prototype.bark = function (sound) {
return this.name + “says” + sound;
// better: extend existing prototype
Computer Science and Engineering  The Ohio State University

Methods in Prototype
Computer Science and Engineering  The Ohio State University
r = new Dog()
Dog.prototype
bark constructor
return this.name
+ “says” +sound;
this.name = x;
this.age = a;

Idiom: Classical Inheritance
Computer Science and Engineering  The Ohio State University
function Animal() { … };
function Dog() { … };
Dog.prototype = new Animal();
// create prototype for future
Dog.prototype.constructor = Dog;
// set prototype’s constructor
// properly (ie should point to

Setting up Prototype Chains
new Animal()
constructor
Computer Science and Engineering  The Ohio State University
constructor

Objects as associative arrays
Partial maps from keys to values
Can dynamically add/remove properties Can iterate over properties
Method = function-valued property Keyword this for distinguished parameter
Constructor = any function
Prototypes are “parent” objects
Delegation up the chain of prototypes Prototype is determined by constructor Prototypes can be modified
Computer Science and Engineering  The Ohio State University

Zen proverb
Computer Science and Engineering  The Ohio State University
The quieter you become, the more you can hear.

Objects are Everywhere
Computer Science and Engineering  The Ohio State University
Global variables in JavaScript are a
Implicitly part of some “global object”, provided by
execution environment
See FF Developer Tools: Console

Window Object
Computer Science and Engineering  The Ohio State University
For JavaScript running in a browser,
implicit global object is the window
>> this->Window
Many properties, including
location (url of displayed document) status (text in status bar of browser) history
innerHeight, innerWidth
alert(), prompt()
document (tree of displayed document)
     

Document is a Tree
Computer Science and Engineering  The Ohio State University
attr name:
attr value
charset: utf-8
href: planet.html
src: pic.png alt: a globe
Something Short and Sweet

DOM: “Document Object Model”
Computer Science and Engineering  The Ohio State University
DOM is a language-neutral API for working with HTML (and XML) documents
Different programming languages have different bindings to this API
But all are similar to JavaScript’s API
In JavaScript, tree nodes -> objects
A tree node (i.e. an element with attributes)

A JavaScript object with many properties
{ tagName: “INPUT”,
type: “text”,
name: “address”, /*lots more…*/ }

DOM History
Ad hoc DOM existed from the beginning of JavaScript Core purpose of client-side execution: Enable user interaction with the document
Need a connection between programming language (JavaScript) and the document
DOM 1 specification (W3C) in ’98 Standardized mapping tree -> objects and functions for modifying the tree
DOM 2 (’00): added styles and event handling DOM 3 (’04): fancier tree traversal & indexing schemes
DOM “4” (’15…):
Actually just a “living document”
Some non-backwards-compatible changes
Computer Science and Engineering  The Ohio State University

Simplest Mapping
Computer Science and Engineering  The Ohio State University
write(): outputs text to document body
anchors: all anchors in document links: all links in document getElementById(string): find a node etc…
forms: array of forms in a page elements[]: array of widgets in a form

Document is a Tree
Computer Science and Engineering  The Ohio State University
attr name:
attr value
charset: utf-8
href: planet.html
src: pic.png alt: a globe
Something Short and Sweet

Node is a JavaScript Object
Computer Science and Engineering  The Ohio State University
parentNode, childNodes, firstChild, lastChild,
nextSibling, previousSibling
Properties
appendChild(node), removeChild(node),
insertBefore(node)
hasAttribute(attr), removeAttribute(attr), getAttribute(attr), setAttribute(attr) getElementsByTagName(name)
XML lower case (“a”), HTML upper case (“A”) attributes, name, id, class
Hyphenated property in CSS (e.g., “font-size”) become
camelCase in JavaScript (e.g., “fontSize”)

How to Find a Node in Tree
Computer Science and Engineering  The Ohio State University
1. Hard coding with “flat” techniques
Array of children
document.forms[0].elements[0]
Downside: too brittle
If the document structure changes a little, everything breaks
2. Using an element’s name attribute


In JavaScript:
document.address.zip
Downside: direct path still hard coded

How to Find a Node in Tree
Computer Science and Engineering  The Ohio State University
3. To get a unique element: document method getElementById

In JavaScript
document.getElementById(“shipping”)
Downside: every element you want to find needs unique ID
4. Combination: element ID for form, arrays for options in selection element

Car
Truck
Bike
var numChecked = 0;
var elt = document.getElementById(“wheels”);
for (i = 0; i < elt.vehicles.length; i++) { if (elt.vehicles[i].checked) numChecked++; Computer Science and Engineering  The Ohio State University Interactive Documents Computer Science and Engineering  The Ohio State University To make a document interactive, you Widgets (ie HTML elements) Buttons, windows, menus, etc. Mouse clicked, window closed, button clicked, etc. Event listeners Listen (ie wait) for events to be triggered, and then perform actions to handle them Events Drive the Flow of Control Computer Science and Engineering  The Ohio State University This style is event driven programming Event handling occurs as a loop: Program is idle User performs an action Eg moves the mouse, clicks a button, types in a text box, selects an item from menu, ... This action generates an event (object) That event is sent to the program, which Code executes, could update document Program returns to being idle Handling Events Mechanism Computer Science and Engineering  The Ohio State University Three parts of the event-handling mechanism Event source: the widget with which the user interacts Event object: encapsulated information about the occurred event Event listener: a function that is called when an event occurs, and responds to the event event object HTML Element aHandler() Programmer Tasks Define an event handler Any function can be an event handler Often need information about the triggering event in order to know what response is needed Register handler with source element Detect event and invoke handler Ha! Just kidding, you do NOT do this Computer Science and Engineering  The Ohio State University Simple Example: Color Swaps Computer Science and Engineering  The Ohio State University

This page illustrates changing colors


Color Swaps (JavaScript)
Computer Science and Engineering  The Ohio State University
function foo(place, color) {
if (place === “bg”)
document.body.style.backgroundColor =
document.body.style.color = color;

Event Propagation
Elements are nested in tree
When an event occurs, which element’s handler(s) is(are) notified? First, propagation path is calculated: from root to smallest element
Then event dispatch occurs in 3 phases 1. Capture (going down the path)
2. Target (smallest element)
3. Bubble (going up the path, reverse of 1)
Computer Science and Engineering  The Ohio State University

http://www.w3.org/TR/DOM-Level-3-Events/
Computer Science and Engineering  The Ohio State University

Bubbling Up
Computer Science and Engineering  The Ohio State University
Usually, handling is done in phase 2
Example: mouse click on hyperlink
Handler for element displays a pop- up (“Are you sure you want to leave?”) Once that is dismissed, event flows up to enclosing

element, then

then… etc. until it arrives at root element of DOM
This root element (i.e. window) has a handler that loads the new document in the current window

Programmer Tasks
Define a handler
Easy, any function will do
Register handler
Multiple ways to link (HTML) tree elements with (JavaScript) functions
Be triggered by the event Ha! Still kidding
Get information about triggering event Multiple (incompatible) ways for handler to get the event object
Computer Science and Engineering  The Ohio State University

Registering an Event Handler
Computer Science and Engineering  The Ohio State University
Three techniques, ordered from:
Oldest (most brittle, most universal) to Newest (most general, least standard)
1. Inline (link in HTML itself)

2. Direct (link in JavaScript)
var e = … //find source element in tree e.onclick = foo;
3. Chained (In JavaScript, browser
differences)
var e = … //find source element in tree e.addEventListener(“click”, foo, false);

Inline Registration (pre DOM)
Computer Science and Engineering  The Ohio State University
Use HTML attributes (vary by element type) For window: onload, onresize, onunload,…
Forms & elements: onchange, onblur, onfocus, onsubmit,…
Mouse events: onclick, onmouseover, onmouseout,…
Keyboard events: onkeypress, onkeyup,…
The value of these attributes is JavaScript code to be executed, Normally just a function invocation Example

Advantage: Quick, easy, universal Disadvantage: mixes code with content

Direct Registration (DOM 1)
Computer Science and Engineering  The Ohio State University
Use properties of DOM element objects onchange, onblur, onfocus,…
onclick, onmouseover, onmouseout,…
onkeypress, onkeyup,…
Set this property to appropriate handler
var e = … // find source element in tree e.onclick = foo;
Note: no parentheses!
e.onclick() = foo; // what does this do? e.onclick = foo(); // what does this do?
Disadvantage? No arguments to handler Not a problem, handler gets event object
Real disadvantage: 1 handler/element

document.getElementsByTagName(“div”);
for (var i = 0; i < x.length; i++) { x[i].onmouseover = function () { this.style.backgroundColor="red" x[i].onmouseout = function () { this.style.backgroundColor="blue" Computer Science and Engineering  The Ohio State University Chained Registration (DOM 2) Computer Science and Engineering  The Ohio State University Each element has a collection of handlers Add/remove handler to this collection var e = ... //find source element in tree e.addEventListener("click", foo, false); Note: no "on" in event names, just "click" Third parameter: true for capture phase Disadvantage: browser incompatibilities e.addEventListener() // FF, Webkit, IE9+ e.attachEvent() // IE5-8 Many browser compatibility issues with DOM and Eg jQuery, Dojo, Prototype, YUI, MooTools,... Solution: Libraries document.getElementsByTagName("div"); for (var i = 0; i < x.length; i++) { x[i].addEventListener ("click", function () { this.act = this.act || false; this.act = !this.act; this.style.backgroundColor = (this.act ? "red" : "gray"); Computer Science and Engineering  The Ohio State University Task: Getting Event Object Computer Science and Engineering  The Ohio State University Most browsers: parameter to handler function myHandler(event) IE: event is property of window Common old-school idiom: function myHandler(event) { event = event || window.event; ... etc ... Again, libraries are the most robust way to deal with these issues Computer Science and Engineering  The Ohio State University DOM: Document Object Model Programmatic way to use document tree Get, create, delete, and modify nodes Event-driven programming Source: element in HTML (a node in DOM) Handler: JavaScript function Registration: in-line, direct, chained Event is available to handler for inspection 程序代写
CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com