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