Prototypal Inheritance and you.

Let’s first start by saying that Javascript is a little interesting when it comes to classes and objects. Technically I think Javascript is basically classless (probably why I like it so much…) but there are class-like activities. Just remember at its root, an Object is a just a unordered collection of key:value pairs. Anything other than strings, numbers, booleans, undefined and null is an object.

Let’s create some objects.

var anObject = {};
anotherObject = new Object();

-or-

function MyObject() {}
var myObject = new MyObject();

 

Now where does Prototypal Inheritance enter into this? Each object has an internal link to another object, known as its prototype.  This other object also has a prototype, and so on until we reach null as its prototype.null ending the chain.

Objects are buckets of properties with links to a prototype object. When access to a property is requested it will look not only at the specific objects property but all the way back up the prototype chain until the property is found or the end of the chain.

Let’s add some methods to the objects.

function MyObject() {}

var myObject = new MyObject();

MyObject.simpleLog = function(value) {
    console.log(value);
}

var difObject = new MyObject();

difObject.simpleLog = function(value){
    console.log('The value is: ', value);
}

difObject.simpleLog("something should go here"); //calls the instance specific method
MyObject.simpleLog("something should go here"); //calls the static Object method
MyObject.prototype.simpleLog = MyObject.simpleLog; //apply the static method to all instances from here on in
difObject.simpleLog("still calling instance method");  //still calls the instance method
var yetAnotherObject = new MyObject();
yetAnotherObject.simpleLog("inherited from MyObject"); //inherited simpleLog() from MyObject
MyObject.simpleLog("I also inherit."); //pre-existing instances also inherit the new function

 

So as you can see when you add a method to the prototype it gets inherited along the prototype chain. There is an order to when this gets used as you can see in the difObject.simpleLog(); call that it uses the local instance method as it does not have to go up the chain to find the one we added with the line MyObject.prototype.simpleLog = MyObject.simpleLog;

Now when we reference methods in JavaScript it is not strictly accurate in the form that other class-based languages. For JavaScript any function that you add as an object property becomes a method for that object.  An inherited function acts just as any other property on that object, including method overriding!

Another key point to remember is what happens to this. Its value points to the inheriting object not back to the prototype object where the function is an own property. Let’s look at another example.

var myObject = {
    staticValue: 40,
    someMethod: function(val) {
      console.log(this.staticValue);
      return this.staticValue + 1;
    }
};

console.log(myObject.someMethod()); //42

var yourObject = Object.create(myObject);

yourObject.staticValue = 20;

console.log(yourObject.someMethod());  //21

 

As you can see once we overwrite a value it will no longer work its way up the chain allowing for differences in the objects after they are created. Very useful! I will be digging deeper into objects and modules in another post.

Maker Square Day 6

Data Structures

Linked List

Singly Linked List

Singly Linked List (see video)

What is a linked list? It is a list where each section of the list knows the name of the next section of the list. Something like a->b->c-X where X is null. If we look at a we know we can get the next value, so a.next would be b. This is interesting because without knowing what is third we can find it by going a.next.next = c because b knows about c. Then we can pull the information from that location a.next.next.info = 3000. You might be saying so what?

Here are some reasons for a linked list.

  • you need constant-time complexity for insertions and deletions from the list i.e. to increase time predictability
  • you don’t know how many items will be in the list. With arrays you might need to re-declare and copy memory if the array grows too large
  • you don’t need random access to any elements
  • you want to be able to insert items in the middle of the list such as a priority queue.

Though there is debate on almost every reason to use it vs another data structure. Hopefully I will learn more and make up my own mind on when I would like to use them and not. For now… just store it and move on.

Tree

Tree Data Structure

Tree Data Structure

A tree is a hierarchical structure with parents and descendants at the very minimum. Not super useful yet, but add in siblings and it gets a bit more exciting. There is a bunch. So I am going to put them in a list… hrmm.

  • Root – The top node in a tree.
  • Parent – The converse notion of a child.
  • Siblings – Nodes with the same parent.
  • Descendant – A node reachable by repeated proceeding from parent to child.
  • Ancestor – A node reachable by repeated proceeding from child to parent.
  • Leaf – A node with no children.
  • See the wikipedia entry for even more good stuff.

Once all of these things go together we can see that now it has some value. Thinking of the DOM right away, but also a great way to store data that has this type of relationship. Grape growers could track down to the grape if they wanted to in a production line. Builders working on a complex structure could be arranged this way with responsibilities being assigned to nodes.

Graph

Undirected Graph

Undirected Graph

We only looked at one type of graph, the undirected  graph.  This is a set of nodes that have a set of unordered pairs called edges linking them.  Think of a community. House A, House B and House C. House B is on the corner of two streets. House A is on one street and House C is on the other. House A and House B share an route, and House B and House C share another route.

So… House A has an edge to House B. House B has an edge to House A and House C. House C has an edge to House B. Clear? okay good. Also that network at the top is a graph.

Some common things to be done with graphs you say? Glad you asked. Add a node. Add/Remove edges. Get Neighbors? Sure list every node that has an edge to me.

Most of this day was spent on finishing up the sprint and going into the extra credit section a bit.

Maker Square Day 4

Video Lecture on Complexity Analysis. Space = memory. Time = when. How does time grow?

An algorithm is a plan that helps you solve problems.

To compare all numbers is n^2 is of quadratic time complexity.

Find largest by finding smallest? On

if sorted list, compare first and last is constant time. Gives an approximation of time, not an actual number. Note, highest order first. Think about it as LARGE(n).

Static analysis = analyse and reason through it with graphing.

Constant = array look up
O(log n) = binary search
linear O(n) = print array;
O(n^2) = find largest (nested for loops)
O(c^n) = guess password of (n) length

Binary Search?

var binarySearch = function(array, ele, start, end){
  var start = start || 0;
  var end = end || array.length-1;
  var midpoint = Math.floor((end + start) / 2);
  if (array[midpoint] > ele){
    return binarySearch(array, ele, start, midpoint-1);
  }
  else {
     return binarySearch(array, ele, midpoint+1, end);
  }
}

Protoypal Classes

Q: Can you think of a way to use prototype chains that might help? Removes extend loops, allows chaining of values and having them push out.

Talking about obj within constructor class is the same as talking about every instance. To create a function for making instances is a line in that function where you create a new instance object (object.create(car.methods)) an object as a prototype and some logic for augmenting the new object with properties that make it unique from other objects in the same class (obj.loc = loc).

Pseudo-classical Classes

new keyword = when new is used before a function it acts in a special mode called constructor mode. (var foo = func() {blah;}; var blah = new foo;) constructor mode sneaks in the this.object.create(car.prototype); and the return this; at the end of the function. Pseudo-class has two parts, the prototype properties to hold similarities  and the constructor function to hold the differences.

Open Source Lecture

Productivity Tip: Look at OctoTree for chrome and git access

To contribute to open source projects is a good thing! You don’t have to be a genius to help out. Look at the larger repos. Think about clarifying comments, adding tests, even making sure the style is consistent. These things are needed and appreciated.

Tips for success. Follow repo styles and conventions. Pay close attention to the commit message conventions. Changes should be a single commit. Well written merge comments will increase the chance of a successful pull request.

Data Structures

Quick review on scope and closure. Scope = set of rules to define value availability lexical scoping. Closure = if you instantiate an object the instantiated object has access to the original object.

Hash Tables

Very similar to an object. 2 components to a Hash table. The storage part and the hashing function.  The hashing function takes a key, and dresses it up so that its always the same dress for the same key. This hashed key equals the location in storage. We must watch for collisions, and distribute as evenly as possible to reduce collisions.