Sunday, February 10, 2019

5.6 Binding Events

The one really nice thing about classes is that they are a nice way of grouping data with the code that manipulates that data. This leads to a very common situation in programming where you want to do something with the data when an event happens. Event-driven programming is where the behavior of a program is structured around events instead of sequences and is the way you typicality approach user-interface related tasks. Combing objects with events seems like a no-brainer but this is where JavaScript starts showing some strangeness. To understand lets write a simple event.

// General function for printing to the web page so results can be seen
// without requiring the console
function printTestLine(s) {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now append the new line to this element
results.innerHTML = results.innerHTML + "
" + s

}

// The timeout method uses a callback which gets called asyncronously
function tickTest(){
printTestLine("Tick Test was called!")
}
setTimeout(tickTest, 1500);

Timing events in JavaScript can be controlled by using a timeout. SetTimeout simply takes a function and a duration in milliseconds which are thousandths of a second. After the duration has expired it will call the function. Note that the timer is not precise and that the delay can be more than the specified amount bur for general usage timeouts are adequate. Running the above would result in a second-and-a-half delay before something was printed.

Now lets write a simple class that will store a value and when a function is called will display that value back.

// A simple class that stores a value and can display the currently stored value when asked to.function Demo() {
this.setValue = function(n) {
this.storedValue = n;
}

this.displayValue = function() {
printTestLine("Stored value is " + this.storedValue);
}

this.displayWithMessage = function(s) {
var str = "NO MESSAGE PROVIDED ";
if (s !== undefined)
str = s;
printTestLine(str + this.storedValue);
}
}

// as this shows, the class works as expected
var demo = new Demo();
demo.setValue(42);
demo.displayValue();
demo.displayWithMessage("Custom message before value ");

This works just fine so using it as part of an event seems trivial but lets try that.

// however, the value does not seem to exist if used as a callback.
setTimeout(demo.displayValue, 2000);
\end{lstlisting}
}

After a couple of seconds delay we get a rather interesting result. This is a byproduct of the way JavaScript calls methods within a function and is something that we will discuss in detail next fortnight. Obviously, this means that we can't use events with classes. But, as this is an obvious necessity, there is a bind function that browsers provide to solve this problem. By simply adding the bind function to the end of the function you are calling you will be able to specify which class the event is for. The function takes the instance of a class to use as it's parameter and does not need to be the calling instance but I can't think of any situation where I wouldn't want to use the same instance.

// this is where binding comes in
setTimeout(demo.displayValue.bind(demo), 2500);

// Binding also helps with parameters.
setTimeout(demo.displayWithMessage.bind(demo), 3000);
setTimeout(demo.displayWithMessage.bind(demo, "Message added in Binding "), 3000);

As can be seen from the demo code, binding can also be used to add additional parameters to a callback function. When dealing with situations such as having multiple buttons being handled by the same logic, this is an incredibly convenient feature of the bind function. But what exactly is the bind function doing? Tune in next fortnight to find out!

Saturday, January 26, 2019

Polymorphism and Duck Typing

Polymorphism is just a fancy way of saying that we can use an inherited class in place of a base class. This is a very important concept in typed languages, but is automatically handled for you in dynamically typed languages like JavaScipt. One of the nicest features of JavaScipt is that you not only can use a child class in place of a parent class, but you can use any class that has the methods and properties that you want to use. This is known as duck typing and is called that from the saying "if it looks like a duck, walks like a duck, and quacks like a duck then it is probably a duck."

The power of polymorphism comes from the ability to call a function that takes a base class with any class that is inherited from that class. For example, lets say we create a function for playing with the pets that we created last section.
 
// Note - See previous section for the Pet classes 

// function for pet class objects
function playWithPet(pet) {
printTestLine("Playing with " + pet.name);
pet.makeNoise();
}

// Pet polymorphism test code
printTestLine("Class polymorphism using inherited pets:");
var cat = new Cat("Abby")
var dog = new Dog("Smokie")
var fish = new Pet("Dora", "Fish")

playWithPet(cat);
playWithPet(dog);
playWithPet(fish);

Notice that we can call this function with any of the pet classes that we created. This is a very important concept as it means that we can create functions that use base classes and they will continue to work with classes that we create in the future giving us a lot of flexibility. Duck typing takes this a bit further by not even requiring the same base type. Lets test this by creating a non-pet duck class.

Duck = function(name) {
this.name = name;

this.makeNoise = function() {
printTestLine(this.name + " Quacks!");
}
}

// Testing duck-typing
printTestLine("---------");
printTestLine("Duck-typing test:");
var duck = new Duck("Daffy");
playWithPet(duck);

As you can see, the only requirement JavaScript has is that the method being called exists. The Duck class did not need to inherit from the pet class nor did it need to implement all the methods in the pet class, just the methods and properties that any function it was being called with requires.

For smaller programs, duck-typing is a very handy feature, but it can result in problems with larger projects. This is why interfaces are often used in place of duck-typing in languages like Java.

Saturday, January 12, 2019

5.4 Inheritance

One of the most powerful and most over-abused features of object oriented programming is the use of inheritance. The basic idea here is that there are a lot of classes of objects that have a lot of features in common. Instead of re-writing the same code repeatedly for similar objects, a hierarchy of related classes can be created. You start with a base class, also known as the parent, that has the base functionality it's children will inherit. To demonstrate this, lets create a base class for pets.

The pet class will have a name for the pet and a species for the pet. Pets will be able to greet their owner, and make a noise. First, lets take a look at the more modern ECMAScript 6 way of doing this. This is set up just like any normal class that we would have created in the previous section.


class E6Pet {
constructor(name, species) {
this.name = name;
this.species = species
}

greet() {
printTestLine(this.name + ", the " + this.species + ", comes to greet you");
}

makeNoise() {
printTestLine(this.name + " makes a noise");
}
}

var fish = new E6Pet("Nemo", "Fish")
fish.greet();
fish.makeNoise();


The old way of creating the base class is also the same way you would create a class using older versions of ECMAScript.

function Pet(name, species) {
this.name = name;
this.species = species;

this.greet = function() {
printTestLine(this.name + ", the " + this.species + ", comes to greet you");
}

this.makeNoise = function() {
printTestLine(this.name + " makes a noise");
}

}

var oldfish = new Pet("Dora", "Fish")
oldfish.greet();
oldfish.makeNoise();

Once you have a class that can be used as a base-class, you can create a new class that inherits the methods and variables of it's parent. This effectively gives you all the code that you have written in the base class. You can then add additional methods and variables allowing the new class to have the functionality of the base class while adding new features to the class. This alone would make inheritance worth doing, but it gets even more powerful. It is possible to override an existing method and replace it with another method that is more appropriate for the class you are creating.

In our example, different pets make different sounds so by overriding  the makeNoise method, we can create species specific noises. We will create a dog and a cat, with each of them having a unique noise and the dog being able to wag it's tail.

ECMAScript 6 makes inheritance very easy as you just use the extends keyword when you are creating a class. Sub-classes can have a different number of parameters, with the super method used to call the original code. Overriding the method is simply the matter of using a method with the same "signature." A method's signature is simply the method name and the particular parameters that make up the method. finally creating a new method is done by having a new method in the class.

class E6Cat extends E6Pet{
constructor(name) {
super(name, "Cat")
}

makeNoise() {
printTestLine(this.name + " Meows!");
}
}

class E6Dog extends E6Pet {
constructor(name) {
super(name, "Dog")
}

makeNoise() {
printTestLine(this.name + " Barks!");
}

wag() {
printTestLine(this.name + " wags his tail!");
}
}

var cat = new E6Cat("Lexi")
var dog = new E6Dog("Scruffy")

cat.greet();
cat.makeNoise();
dog.greet();
dog.makeNoise();
dog.wag();

The old way of inheritance is a bit more confusing as older versions of ECMAScript does not have a way of directly indicating inheritance so the programmer must manually set this up. JavaScript use prototype based inheritance where every class has a prototype that determines which methods it has. This prototype is used by the new operator to set up the class, but the prototype can be modified manually. The result is that there are many ways of setting up inheritance in JavaScript. The most common way is simply assigning the prototype of the class to the prototype of it's parent by using the new function.

function Cat(name) {
this.name = name;
this.species = "Cat";

this.makeNoise = function() {
printTestLine(this.name + " Meows!");
}
}
Cat.prototype = new Pet();

(Dog = function(name) {
this.name = name;
this.species = "Dog";

this.makeNoise = function() {
printTestLine(this.name + " Barks!");
}

this.wag = function() {
printTestLine(this.name + " wags his tail!");
}

} ).prototype = new Pet();

var oldcat = new Cat("Abby")
var olddog = new Dog("Smokie")

oldcat.greet();
oldcat.makeNoise();
olddog.greet();
olddog.makeNoise();
olddog.wag();

You will notice two slightly different styles for doing this. The cat way is the textbook way while the dog way is the way JavaScript code generated by Animate CC does things. You could also manually copy just the methods you are interested in, which can be a handy way of inheriting functionality from multiple different classes.

Inheritance is not just for reducing code duplication, but allows for a powerful technique known as polymorphism which we will be covering next.

Saturday, December 29, 2018

5.3 Constructing Classes

While I have my January game ready, I am at my parent's place while the game is in a different city so I will not be posting it until January 2nd when I return to University.

JavaScript did not have "proper" classes until ECMAScript 6. The problem is that while there is now a class keyword that makes creating classes much easier in browsers that have an ECMAScript 6 complaint version of JavaScript, this is not all browsers. Eventually there will be so few browsers that do not support ECMAScript 6 that using JavaScript classes will make sense, but before that transition takes place, the old way of creating JavaScript classes must be used. The nice thing is that backwards compatibility means that the old way will still work on new browsers.

The ECMAScript 6 way of creating classes is with a class construct. Within this construct we have a constructor which initializes the class and then methods that the class knows. There is some special support for getter and setter methods which I will not be covering here as this book is more focused on older JavaScript but that may be something I cover in a future book. Here is what a soldier class would look like in ECMAScript 6 versions of JavaScript:

// General function for printing to the web page so results can be seen
// without requiring the console
function printTestLine(s) {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now append the new line to this element
results.innerHTML = results.innerHTML + "
" + s

}

class E6Soldier {
constructor(name, rank, serialNumber) {
this.name = name;
this.rank = rank;
this.serialNumber = serialNumber; 
}

printNRS() {
printTestLine("Name: " + this.name + " Rank: " + this.rank +
" Serial Number:" + this.serialNumber);
}
}

printTestLine("ECMAScript 6 tests");
var soldier1 = new E6Soldier("Bob", "Private", 12345);
var soldier2 = new E6Soldier("Doug", "Captain", 23456);
soldier1.printNRS();
soldier2.printNRS();

You will notice that both soldiers simply used the E6Soldier class to build their object. The creation of an object from a class is called instantiation in object oriented terminology. Every object of a particular class is known as an instant of that class. Instances share the same properties and methods, though object specific properties and methods can be manually added to specific objects if desired, but are otherwise independent.

The old way of creating classes is similar to the new way but instead of grouping things into a class structure you are creating a function. This function sets up the properties just like the constructor above did and then sets up all the methods that are used by the class.

function Soldier(name, rank, serialNumber) {
this.name = name;
this.rank = rank;
this.serialNumber = serialNumber;

this.printNRS = function() {
printTestLine("Name: " + this.name + " Rank: " + this.rank +
" Serial Number:" + this.serialNumber);
}
}

Note that it is not necessary to have all the methods defined within the function. Some people actually like defining the methods of a class outside of the class. This is done by using the function's prototype, which is something we will be talking about in more detail in later sections.

Soldier.prototype.changeRank = function(newRank) {
this.rank = newRank;
}

Using the classes is pretty much the same the old way as it is the new way.

var soldier3 = new Soldier("Pete", "Private", 34567);
var soldier4 = new Soldier("Billy", "Captain", 45678);
soldier3.printNRS();
soldier4.printNRS();
soldier4.changeRank("General");
soldier4.printNRS();

The real power of classes comes from polymorphism and inheritance, but that is also where the biggest problems of object oriented programming come from. Next section we will start our exploration of polymorphism and inheritance.

Saturday, December 15, 2018

5.2 Creating Objects

There are a number of ways to create an object. The standard way of creating an instance of a class is to use the new constructor, which we will be covering in the next section. There is a special class that all classes are based off of called Object. This class can be used to create a new basic object which properties and methods can be attached to. To create an object using the new keyword is done as follows:

var myObj = new Object();

Properties can be added to an object by simply giving the property a value. This adds an interesting quirk to JavaScript programs as null indicates that an existing property has no current value attached to it while undefined means that the indicated property has not been attached to an object. For people use to typed languages this can be confusing as undefined and null are different things. You can check to see if a property is defined by using the following:

if (myObj.variable === undefined) 
// handle undefined variable here

Object Oriented programmers generally refer to functions that are part of an object as methods. As was discussed in Chapter 3, functions can be assigned to a variable. This means that to add a method to an object you simply need to add it as you would any other property. You can create a new function specifically for the object or you can use an already existing function and simply attach it to the object.

// here is a comomon function that will be shared by multiple objects
function printNRS() {
// we are grabbing an html element
var results = document.getElementById("testResults");
// now we are adding the info onto the text contained within the element
results.innerHTML += "
Name: " + this.name + " Rank: " + this.rank +

" Serial Number:" + this.serialNumber; 
}

// Build first soldier by using an object and adding properties to it
var soldier1 = new Object();
soldier1.name = "Bob"
soldier1.rank = "Private";
soldier1.serialNumber = 12345;

// Methods can be added too
soldier1.printNRS = printNRS;
soldier1.makeCaptain = function() { this.rank = "Captain"};

Notice that in order to reference a property of the object that is calling the function, the this keyword is used. Scope works a bit different than in most other languages and is function based. This is why the function printNRS can access the properties of the object as it is called from that object so holds the object's scope. We will come back to this topic in a bit more detail when we cover closures in a later section.

As mentioned earlier, there is more than one way of creating an object. JavaScript has a shorthand way of creating properties and pairing them to values so that it is easier to create objects with multiple properties initialized. This feature of JavaScript was expanded upon to come up with the JSON data transfer format which is why many people refer to creating objects using key : value pairs as being in JSON format. This shorthand method simply lets you define the contents of the object by using {} to indicate the object and then placing the property name followed by a colon followed by the value. It is possible to have functions within this declaration. Once the object is created you can add additional properties or method as you did with the soldier1 object. So, lets create a second soldier:

var soldier2 = { name : "Doug", rank : "Captain", 
serialNumber : 23456, 
makeMajor : function() {
this.rank="Major"

};
// adding addtional methods, such as this common method, is possible
soldier2.printNRS = printNRS;

JSON is an acronym and stands for JavaScript Object Notation. It was originally created as a data transfer standard between JavaScript and whatever language is being ran on the server-side. The idea is that objects get converted into strings to be transferred then converted into objects at the destination. It is much simpler and more condensed than XML so has largely replaced XML usage. If you are receiving JSON strings from a server or other input file you can easily convert the strings into JavaScript by using the built-in JSON class as is done to create our third soldier.

var soldier3 = JSON.parse('{ "name" : "Billy", "rank" : "General", "serialNumber" : 42}');
soldier3.printNRS = printNRS;

Manually creating multiple versions of what is essentially the same object does seem like a lot of work. There is a better way which we will cover in the next section.

Saturday, December 1, 2018

C5.1 Namespaces

When you are writing small programs you may never run into the namespace problem. Once you start using libraries, especially if you use multiple libraries, the namespace problem comes into play. Let us say you had a library that had a function for displaying hello. This library is called namespaceIssue.js and may look something like this:

message = "Hello!"
function sayHello() {
return message
}

Now lets say you wrote the following page that uses the library:

<!DOCTYPE html>

Namespace issue demo


Namespace issue demo









You would expect this program to display the words hello and goodbye. This is not what happens. Instead, it displays goodbye twice. Why? The library used the variable message to store the message that the sayHello function would display. The script in the html file uses message to store the goodbye message to display. It overwrites the variable which the library was using. For a small program like this it is a trivial problem to solve, but when the size of your program increases, especially if you are using code provided by third parties, this problem of variable (and function name) collision becomes a huge problem.

The solution to this problem is namespaces. The idea here is that you have a unique namespace for your program and all the variables for that program go into that namespace. Since each namespace is separate, you can have the same variable name in each of the namespaces without any conflict. In JavaScript, namespaces are created by creating a object with the name of the namespace. Here is the demo above re-written to use namespaces.

namespceUsed = {}
namespceUsed.message = "Hello World!"

function sayHello() {
return namespceUsed.message
}

It is possible to nest namespaces by having another namespace object as part of a namespace object. This is very commonly done to have library namespaces stored under a single unique namespace that you have control of. The convention is to use your domain as the unique name with appropriate names for the libraries under that domain. Some companies will take this a step further by having the root domain as the first namespace object, followed by their domain, followed by their library. This leads to the problem of declaring a namespace without overwriting other namespaces. The solution is to use the following way of declaring a namespace:

com = com || {}com.spelchan = com.spelchan || {}

It is a good habit to use namespaces for any script that you are loading. I generally don’t bother with the com root namespace but if Spelchan was a more common word, then it may be a good idea. 


Saturday, November 17, 2018

Chapter 5 Overview

Object Oriented programming has become the predominant way of developing software today. While there are some people who believe that object-oriented programming (OOP) is a misstep, there are also people who quite dogmatic about OOP. Both of the Universities I have attended tend to favor the OOP approach but there is starting to be a look at the alternatives to OOP, with functional programming gaining traction. I am a bit more flexible when it comes to programming believing that methodologies, like languages, are tools and one should try and use the appropriate tool for the problem they are dealing with.

Object Oriented approaches are so common, however, that no matter what your stance on OOP is, you should at least be familiar with the concepts behind it. This section of the book takes a look at the core OOP features that JavaScript supports. Unfortunately, like a lot of things about JavaScript, things are not as straightforward as they should be. While JavaScript has always had support for Objects, the language itself did not explicitly support OOP constructs until the ECMAScript 6 standard was released. This means that older browsers do not support the new language keywords but there are a shrinking number of people who use those browsers. It also means that there is a lot of legacy code out there that does OOP the hard way. These techniques are still valid so it is wise to at least be familiar with them.

In this chapter we will look at a number of OOP related concepts looking at what the idea behind the concept is, how ECMAScript 6 supports that concept, and the "old" way of handling the concept.

To start with, in the "NameSpace" section we will be looking at the name space problem and how to get around it. Even if you are not into the other OOP concepts, name spaces are something that ALL non-trivial programs should use.

It goes without saying that objects are important to object-oriented programming so we will then revisit creating objects in "Creating Objects". This will be followed by "Constructing Classes". Classes are what most OOP languages use to define objects with a class keyword being something that was missing from JavaScript until the ECMAScript 6 standard was released.

One of the more powerful, albeit over-abused, features of object oriented programming is the use of inheritance. This allows you to create new classes based off of existing classes without needing to write most of the functionality and will explained in the "Inheritance" section. Polymorphism is how OOP languages take advantage of inheritance by letting you use a child class in place of a parent class. JavaScipt uses a variant of polymorphism known as Duck Typing which gives you a lot of flexibility and power but has some downsides. These issues will be covered in "Polymorphism and Duck Typing".

JavaScript handles classes a bit different from most other object oriented languages. This leads to a strange issue when trying to use an objects function as a call-back. This issue can be solved using something known as binding, which we will explain in a section strangely named "Binding".

What allows JavaScript to bind functions actually is a very powerful construct known as a closure. Closures are a bit confusing and you may not want to use them in your programs, but they are an important JavaScript technique so I will be covering them in the "Closures" section.

And that should cover all the object oriented JavaScript knowledge that you will need for the remainder of this book.