JavaScript II

Objects

  • Objects in JavaScript are declared using curly braces
    object = 
    {
      property1: value1,
      property2: value2,
      .
      .
      .
      propteryN: valueN
    }
    
  • Objects can hold a mixture of properties and functions
  • Property names can be anything
    • If you wish access the property using object.property they need to be a valid variable name
    • All properties can always be acessed by using object[property]
  • Objects are mutable and can have new items added like so:
    object = {}
    object.newProperty = newValue;
    

Objects Examples

In [2]:
var student = {
    name: "Bryan Wilkinson",
    courses: ["473, 478","671","679"],
    "Proposal Title": "Improving the Computational Representation of Scalar Adjectives",
    print: function(){
        console.log("Hello")
    }
}
In [3]:
student.name
Out[3]:
'Bryan Wilkinson'
In [4]:
student.courses
Out[4]:
[ '473, 478', '671', '679' ]
In [5]:
student.print()
Hello
In [6]:
student."Proposal Title"
SyntaxError: Unexpected string
    at run ([eval]:192:19)
    at onMessage ([eval]:63:41)
    at process.EventEmitter.emit (events.js:98:17)
    at handleMessage (child_process.js:318:10)
    at Pipe.channel.onread (child_process.js:345:11)
In [7]:
student["Proposal Title"]
Out[7]:
'Improving the Computational Representation of Scalar Adjectives'

Moving Towards OOP

  • So far we can group related pieces of data.
  • How do we make methods that use that object?
    • this keyword
  • How do we make classes
    • Prototypes
    • ES6 provides class definitions that hide prototyping

This keyword

  • this does not always refer to the calling object
  • In the following two situations, it does
    {
          property1: value1,
          property2: value2,
          method1: function(){
              doSomething(this.property1)
          }
      }
    
var object = {
        propertyA: valueA,
        propertyB: valueB
    }

    object.methodA = function(){ doSomething(this.propertyA)}

This Examples

In [8]:
var student = {
    name: "Bryan Wilkinson",
    courses: ["473","478","671","679"],
    "Proposal Title": "Improving the Computational Representation of Scalar Adjectives"
}
In [9]:
student.print = function(){
    
    console.log(this.name + " has taken " + this.courses.join(", "))
}
Out[9]:
function (){
    
    console.log(this.name + " has taken " + this.courses.join(", "))
}
In [10]:
student.print()
Bryan Wilkinson has taken 473, 478, 671, 679

Prototypes

  • In Javascript a prototype is a default value for an object
  • By default, the objects prototype is Object.prototype
  • There are many ways to use this prototype to create a class

Prototypes with Object.create()

  • The most explicit way to use prototypes is to create a default object
In [11]:
var studentPrototype = {
    name: "I need a name",
    courses: [],
    addCourse: function(course){
        this.courses.push(course)
    },
    print: function(){
            console.log(this.name + " has taken " + this.courses.join(", "))
    }
    
}
In [12]:
studentPrototype.print()
I need a name has taken 
In [13]:
var bryan = Object.create(studentPrototype)
In [14]:
bryan.print()
I need a name has taken 
In [15]:
bryan.name = "Bryan Wilkinson"
Out[15]:
'Bryan Wilkinson'
In [16]:
bryan.addCourse('679')
In [17]:
bryan.print()
Bryan Wilkinson has taken 679
In [18]:
studentPrototype.print()
I need a name has taken 679

Prototypes with Constructors

  • It is cleaner to define a constructor that will always give each instance its own properties
In [20]:
function Student(name){
    this.name = name
    this.courses = []
    this.addCourse = function(course){
        this.courses.push(course)
    },
    this.print = function(){
            console.log(this.name + " has taken " + this.courses.join(", "))
    }
}
In [21]:
var bryan = new Student("Bryan Wilkinson")
bryan.addCourse("679")
bryan.print()
Bryan Wilkinson has taken 679
In [22]:
var bryan2 = new Student("Bryan Wilkinson")
bryan2.addCourse("673")
bryan2.print()
Bryan Wilkinson has taken 673

Other uses of Prototype

  • Prototypes can be used to create inheritance
    Person = {
      name: "I need a name"
    }
    Student = {
      course: []
    }
    Student.prototye = Object.create(Person)
    
  • Prototypes can be used to modify objects and classes after their creation

Adding methods to a class using prototype

In [23]:
String.prototype.alternate = function(){
    var method = String.prototype.toUpperCase
    var nextMethod = String.prototype.toLowerCase
    var chars = []
    for(var i = 0; i < this.length; i++){
        var char = this[i]
        chars.push(method.call(char))
        var temp = method
        method = nextMethod
        nextMethod = temp
    }
    return chars.join('')
}
Out[23]:
function (){
    var method = String.prototype.toUpperCase
    var nextMethod = String.prototype.toLowerCase
    var chars = []
    for(var i = 0; i < this.length; i++){
        var char = this[i]
        chars.push(method.call(char))
        var temp = method
        method = nextMethod
        nextMethod = temp
    }
    return chars.join('')
}
In [24]:
"abcdefg".alternate()
Out[24]:
'AbCdEfG'
In [25]:
var str = "Test String"
In [26]:
String.prototype.getFirst = function(){
    return this[0]
}
Out[26]:
function (){
    return this[0]
}
In [27]:
str.getFirst()
Out[27]:
'T'

Adding new Methods to existing types practice

  • Add a method to Array named dequeue that calls Array.shift()
In [33]:
Array.prototype.dequeue = Array.prototype.shift
Out[33]:
function shift() { [native code] }
In [34]:
Array.prototype.dequeue2 = function(){
    return this.shift()
}
Out[34]:
function (){
    return this.shift()
}
In [ ]:
 
In [29]:
var arr = [1,2,3,4]
In [31]:
arr.dequeue()
Out[31]:
1
In [32]:
arr
Out[32]:
[ 2, 3, 4 ]
In [35]:
arr.dequeue2()
Out[35]:
2
In [36]:
arr
Out[36]:
[ 3, 4 ]

Intro into HTML

  • HTML is a way to add structure to text
  • Originally did very basic things like indicate links and section headings
  • Now contains many more elements: buttons, textboxes, images, videos, etc.
  • Primarily is concerned with what the document is made of, not how it looks

Basic HTML Document

<!DOCTYPE html> <!-- Needed to indicate we are using HTML5 -->
<html>
    <head>
        <!-- Many Javascript includes go here -->
        <script src="location"></script>

        <!-- Can also write your own code here -->
        <script>
            console.log("This is JavaScript");
        </script>
    </head>
    <body>
        <h1>Document Definition</h1>
        <p id="identifier">This is where we put the parts of the document</p>
    </body>
</html>

Putting Them Together

  • JavaScript has built in methods to get access to the parts on an HTML document
  • One of the most useful methods is document.querySelector which allows you to select HTML elements based on class or id name along with other properties
  • JavaScript can also be used to add to an existing HTML document through many functions

HTML + JS Example

In [1]:
%%html
<html>
    <head>
        <!-- Include a library, called underscore.js that has a shuffle function built in so I don' have to write one -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
        <script>
            var words = ['hot','cold','freezing','warm']
            //Shuffle the words
            words=_.shuffle(words)
            
            //Add them to the container
            for(var i = 0; i < words.length; i++){
                document.querySelector("#container").insertAdjacentHTML("beforeend","<p>" + words[i] + "</p>")
            }
        </script>
    </head>
    <body>
        <!-- This is where we are going to place the words -->
        <div id="container">
        </div>
    </body>
</html>

HTML + JS Practice

  • Write an HTML document with JavaScript that adds the paragraph "Hello, World!" to the document
  • Write an HTML document with JavasSript that will print out the squares of the numbers 1 through 10, each in its own paragraph
In [3]:
%%html
<html>
    <head>
        <script>
            document.querySelector("#here").insertAdjacentHTML("beforeend","Hello World!")
        </script>
    </head>
    <body>
        <div id="here">
        </div>
    </body>
</html>
In [4]:
%%html
<html>
    <head>
        <script>
            var num = 1;
            while(num < 11){
                document.querySelector("#here2").insertAdjacentHTML("beforeend","<p>" + num * num + "</p>") 
                num++
                }
        </script>
    </head>
    <body>
        <div id="here2">
        </div>
    </body>
</html>

Basic HTML Element Reference

In [13]:
%%html
<html>
    <head>
    </head>
    <body>
        <!-- A div is used to group a set of elements together -->
        <div>
            <p>The paragraph tag sets off different paragraphs of text from each other</p>
            <h1>This is a level 1 heading</h1>
            <h2>There are six levels of headings: 2</h2>
            <h3>3</h3>
            <h4>4</h4>
            <h5>5</h5>
            <h6>6</h6>
            <p>Lists are made using the ol(ordered list) or ul(unordered list) tags</p>
            <ol>
                <li>This is good for an numbered outline</li>
                <li>Or a set of instructions</li>
            </ol>
            <ul>
                <li>UL creates items denoted with bullet points</li>
            </ul>
        </div>
        
        <div>
            <h2>Form Elements</h2>
            <p>Form elements are used to collect input from a user. Originally this was always
               sent to a server, but now we can respond to input using JavaScript, specificaly event. </p>
            <label>This is a text box: </label> <input type="text"/>
            <div>
            <input type="button" value="This is one way to make a button"/>
            <button>This is nicer I think</button>
            </div>
            <div>
               <input type="radio"/><label>Radio Button</label>
               <input type="radio"/><label>Radio Button</label>
               <input type="radio"/><label>Radio Button</label>
            </div>
            <div>
               <input type="checkbox"/><label>Checkbox</label>
               <input type="checkbox"/><label>Checkbox</label>
               <input type="checkbox"/><label>Checkbox</label>
            </div>
            <label>This is a dropdown</label>
            <select>
                <option>Option 1</option>
                <option>Option 2</option>
            </select>
        </div>
        
        <div>
            <h2>Tables in HTML</h2>
            <p> For a long time, tables were used in HTML for both data and page layout. 
                They should only ever be used to display data that belongs in a table.</p>
            <table>
                <!-- To specify table headers -->
                <thead>
                    <tr>
                        <th>Heading 1</th>
                        <th>Heading 2</th>
                        <th>Heading 3</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- TR is a table row -->
                    <tr>
                        <!-- TD is a table cell in a row -->
                        <td>Data 1</td>
                        <td>Data 2</td>
                        <td>Data 3</td>
                    </tr>
                    <tr>
                        <!-- TD is a table cell in a row -->
                        <td>Row 2</td>
                        <td>Row 2</td>
                        <td>Row 2</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>

The paragraph tag sets off different paragraphs of text from each other

This is a level 1 heading

There are six levels of headings: 2

3

4

5
6

Lists are made using the ol(ordered list) or ul(unordered list) tags

  1. This is good for an numbered outline
  2. Or a set of instructions
  • UL creates items denoted with bullet points

Form Elements

Form elements are used to collect input from a user. Originally this was always sent to a server, but now we can respond to input using JavaScript, specificaly event.

Tables in HTML

For a long time, tables were used in HTML for both data and page layout. They should only ever be used to display data that belongs in a table.

Heading 1 Heading 2 Heading 3
Data 1 Data 2 Data 3
Row 2 Row 2 Row 2