Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

2022-05-09

Trampolines - fun way to make recursion not stack overflow

(We'll use JavaScript for today, running in the Firefox developer console.)

No doubt when you learned recursion, you learned that each recursive function call uses stack space to do its work.  There's only so much stack space.  So unless your programming language has a special feature (called tail call elimination), a recursive function can eventually exhaust all stack space, leading to the famous stack overflow error (not the web site).

For example, let's write a loop to sum up numbers from 0 up to some N like this:

let sum = 0;
for (let i = 0; i < 10000; ++i) sum += i;
console.log(sum); // prints: 49995000

Now a recursive version might look like this:

const loop = function(i, sum){
  if (i < 10000){
    sum += i;
    return loop(i + 1, sum);
  } else {
    return sum;
  }
};
console.log(loop(0, 0)); // prints: 49995000

As you can see, a loop is just a recursive function call.

The above is a nice, simple demo of converting a loop to recursion.  But if instead of summing up to 10,000, we sum up to 100,000, then the loop prints 4999950000.  But the recursive function prints:

Uncaught InternalError: too much recursion

With a link to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion

Trampolines

No surprise, like the title says, trampolines can fix this!

The key is to not allow the loop function to run loop(i + 1, sum), because that'd consume stack space!  Instead, the loop function will return a function called a thunk.  That thunk function, when run, will run and return loop(i + 1, sum).  This also means a thunk can return a thunk!

The function that runs loop, and any thunk functions, is called a trampoline.  That's because the thunk function the trampoline runs may return a thunk, and if so, that thunk will get run too.  The thunks keep bouncing off of the trampoline function.  Until one day a thunk returns a value instead of a thunk!  Then the trampoline's job is done, and that value is returned.

Because the thunk itself only ever uses a single "frame" of space on the stack, rather than recursively using more and more stack space with recursive function calls, and so the stack overflow error is avoided.

Here's how the code will look:

const loop = function(i, sum){
  if (i < 100000){
    sum += i;
    let thunk = ()=>{return loop(i + 1, sum)};
    return thunk; // rather than returning loop(i + 1, sum)
  } else {
    return sum;
  }
};
 

const trampoline = function(){
  let tv = loop(0, 0);
  while (typeof tv === 'function'){
    tv = tv(); // returns either a thunk function or a value
  }
  return tv;
};
 

console.log(trampoline()); // prints: 4999950000

Trampolines running thunk-returning thunk functions is a generic technique that's applicable in other languages and situations too!


Tail Call Elimination: no need for trampolines

If your programming language has full support for an optimization called Tail Call Elimination, the above trampoline technique is completely unnecessary.

It turns out JavaScript at one point had this optimization planned.  It was to be an "invisible" opportunistic tail call optimization (TCO).  Meaning that if you correctly wrote a proper recursive function call in tail position, then TCO would kick in, and it wouldn't consume stack space (thus no stack overflow).

TCO is currently only available on Apple's Safari browser and on iOS [1].

Google's V8 team apparently came to the conclusion that TCO makes the wrong tradeoff.  Because it's an opportunistic optimization, it's very easy for a programmer to write code they think would get TCO, but actually won't, and it can be very difficult to discover the error during testing.  They advocated for an explicit syntactic way to designate a recursive function call as requiring tail call elimination.  But... well, it all fell by the wayside and was never picked back up [2].

Interestingly, the Clojure programming language's creator, Rich Hickey, basically made the same argument.  In Clojure, recursive function calls requiring TCO must be written explicitly with a recur syntax.  In that case, no trampoline is needed, and the recursive function call won't overflow the stack.

 

[1] https://kangax.github.io/compat-table/es6/

[2] https://stackoverflow.com/a/42788286

2019-07-23

Create React Native App using TypeScript compiled with Babel


Here's every step to creating a React Native app, written in and type checked with TypeScript, but compiled with Babel 7.

You're assumed to have some proficiency with using the terminal.

Tools to Install on your PC

I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
  1. Install Homebrew.
    It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
  2. Install Node thru brew.
    Installing Node should include the NPM package manager with it, which is needed below.
  3. Some say to next install Yarn thru brew.
    Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
  4. Fix NPM if you installed Yarn.
    I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
  5. Install React Native CLI thru npm:$ npm install -g react-native-cli
    This is basically a template that creates a RN project for you to start from.
[1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

New Project with React Native

1. Create a React Native project:
$ react-native init CoolProject

1.5. Upgrade core-js:
I got an error like this:
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

You just need to upgrade core-js.  Go into your CoolProject folder and run:
npm install --save core-js@^3

2. cd CoolProject to go into the new project's root directory, then install Babel:
$ npm install --save-dev @babel/core @babel/cli
I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

3. Create a lib folder in the project root.
$ mkdir lib
The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

2019-03-25

Book Review: The JavaScript Handbook by Flavio Copes

If you're a competent programmer but have been away from JavaScript for some time and want an extremely brief overview of the updates to JavaScript, in bite size form, then this book (The JavaScript Handbook) is for you.

Flavio goes over all the new features in JavaScript from ES6 to ES2018. Listing out each feature or change and giving an extremely brief description of it.

This book reads like a collection of very short blog posts though. And would benefit from more editing, both on a sentence level and on an overall topic cohesiveness level. That's a small nitpick in what is overwise a good set of writing.

There's definitely two major parts to the book. First part is extremely brief in describing the changes in each version of ECMAscript.

Second part basically goes over all the changes, again, but this time in more detail. Not a lot more, but sufficient for a competent programmer to know enough.

E.g. if you don't know that much about async and promises on a conceptual level, this book isn't going to teach you enough to really use those features productively.

Or if you don't really know the problems with the "this" keyword in JavaScript, the book's description of it in relation to how it works and how it's changed with arrow functions isn't the most enlightening. Some sentences on it, superficially without a deeper understanding of how programming languages work, are downright contradictory sounding.

All in all though, I went through it cover to cover, and the book does a good job for reviewing changes to JavaScript for the competent programmer.

For next to free (i.e. email signup), it's hard to beat.

2019-03-20

How to migrate ReactXP App to make an Electron Desktop App

ReactXP comes with a few sample apps. The TodoList app is the most developed and closest to the structure of a production app written in TypeScript, but doesn't target Electron.  Here's how to migrate it to run on Electron so it could work as a desktop app.

I'm on a Mac, but Electron is cross platform with Windows and Linux so it should work there too.  ReactXP 1.6.x is current right now (hilariously, it upgraded from 1.5.x just as I was working on this and it introduced some new error so this migration is totally in beta).

Strategically, the idea is ReactXP can already directly target the web via React (in addition to native iOS, Android, and Windows via React Native).  So we just target the web with ReactXP, modify the web page loader to run in Electron, and modify some code so it doesn't assume it's running at the root of a web server.

Make TodoList into a web app. Run it on a local dev web server

First, use git to clone the ReactXP repository:

git clone https://github.com/microsoft/reactxp

In the reactxp/samples directory, you'll find the TodoList app. Open it:

cd reactxp/samples/TodoList/

Install Electron into it:

npm install --save-dev electron

Now we need a web page to load the app into Electron.  We'll use the default one from Electron quick start.  Just copy the main.js from electron-quick-start into the TodoList folder, and rename it to electron-main.js just for clarity.

2019-03-09

Maximally Cross Platform with React?

Once upon a time, going cross platform meant making an application that ran on both Macs and Windows, and maybe Linux/Unix if you're into that crowd.

Now everything is fragmented and compartmentalized.  Consider what "platforms" there are now for making apps:

  1. desktop web browsers --- i.e. Chrome, Firefox, Safari, vs Edge --- further divided by Macs, Windows, and Linux (at least for browsers that are cross platform, ha!)
     
  2. mobile web browsers --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
     
  3. Electron desktop apps --- i.e. Macs, Windows, vs Linux (built with web browser technology)
     
  4. native desktop apps --- i.e. Macs, Windows, vs Linux
     
  5. native mobile apps --- i.e. iOS vs Android --- further divided by phone vs tablet display sizes
Some of the above differences are a matter of building user interfaces sized for use on that display size, while other differences are a matter of framework (e.g. Cocoa vs Android SDK).

But at worse, that's still 26 different platforms to build for!  There are technologies that help bridge the divide, and one family of such tech is called React.

Here's a survey of some React based technologies and which platforms they work well for.


2019-03-06

Create React Native App using TypeScript with Babel and Expo

(updated 2019-07-23 for clarity)

Here's every step to creating a React Native app (with or without Expo), written in and type checked with TypeScript, but compiled with Babel 7.

You're assumed to have some proficiency with using the terminal.

Tools to Install on your PC

I'm on a Mac, but the steps shouldn't be much different on Ubuntu Linux or Windows.
  1. Install Homebrew.
    It's a package manager for Macs, and Linux too, but if you're on Ubuntu or Debian, I suggest just use the built-in one like APT.
  2. Install Node thru brew.
    Installing Node should include the NPM package manager with it, which is needed below.
  3. Some say to next install Yarn thru brew.
    Yarn is yet another node package manager... you can skip this if you want, it's not strictly needed, and I won't use Yarn in this tutorial.
  4. Fix NPM if you installed Yarn.
    I actually mentioned Yarn at all only because with Homebrew, you might now need to fix the Node NPM install as it might be broken by installing yarn.  Simply[1] run: yarn global add npm.  Remember, we don't need Yarn in this tutorial though.
  5. Install Expo thru npm:$ npm install -g expo-cli

    Expo is apparently kind of a mini-platform for running React Native apps, and makes it easy to test a React Native app on devices through its Expo app, or on Macs and PCs without resorting to an Android or iOS emulator (which is great, because those emulators are dreadfully slow in my experience).  Plus installing Expo should include React Native with it.
  6. Install React Native CLI thru npm:$ npm install -g react-native-cli
    This is basically a template that creates a RN project for you to start from.
[1] https://stackoverflow.com/questions/33870520/npm-install-cannot-find-module-semver/49422151#49422151

New Project with React Native or Expo

1. Create a React Native project (possibly thru Expo):
$ expo init CoolProject
or alternatively without Expo:
$ react-native init CoolProject

1.5. Upgrade core-js:
I got an error like this:
warning react-native > create-react-class > fbjs > core-js@1.2.7: core-js@<2.6.8 is no longer maintained. Please, upgrade to core-js@3 or at least to actual version of core-js@2.

You just need to upgrade core-js.  Go into your CoolProject folder and run:
npm install --save core-js@^3

2. cd CoolProject to go into the new project's root directory, then install Babel:
$ npm install --save-dev @babel/core @babel/cli
I assume this will install for you Babel 7 or above.  We'll need it later to migrate to TypeScript.

3. Create a lib folder in the project root.
$ mkdir lib
The lib folder will be used to contain the App's JavaScript files. Traditionally, the folder would be called "src", but looking forward, these JavaScript files eventually will be produced by the TypeScript compiler for us.

So instead, we're going to reserve "src" for later when we migrate to TypeScript, instead of calling it "src" right now when we're still dealing with just JavaScript JS, or JSX, files.

Separating the TypeScript and the compiled JavaScript files is a technique to avoid in-source builds (a usual technique used in compiled languages like C++: see e.g. in-source vs out-of-source builds).

2016-07-11

JavaScript OOP inheritance explained with diagrams


We're not talking about ES6 classes today.  Just ES5 JavaScript object-oriented programming.

## Prototypal inheritance

People say there's at least these **3 big features of OOP** that distinguishes OOP from other styles of programming:

1. Encapsulation
2. Polymorphism
3. Inheritance

We're going to focus on the last item today.

OOP in JavaScript isn't intrinsically class-based in the style of Java.  I assume you already know a thing or two about OOP in terms of Java or Python, or similar though.

Instead, **JavaScript OOP is prototype based**.

That means you'd just make an object `c` as you like it, no class definition required --- but if you must think in classes, imagine making a class `C` and using it to create exactly the one object `c`.

Then when you want another object `s` to inherit from object `c`, you'd just do it, *no class required* --- again if you must, imagine making a class `S` that inherits from `C`, and using `S` to create exactly the one object `s`.

Conceptually, it's simple, but trying to use it productively, with constructors and everything else, and it can get confusing.

Rather than learning how to do class-based OOP in JavaScript (for that, see MDN's [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript) instead), let's try to really understand what JavaScript is doing --- from the bottom up.

## Diving in, bottom up

In JavaScript, everything are objects, even functions.

OK, some things are primitives... forget that, let's just see some code.

By the way, I'm running all the code in the Firefox Console.  Explanations and diagrams are interwoven into the code as comments.

## Cosmic Super Object
Let's start with the "cosmic super" object that all objects
usually inherit from, namely the object stored at 
`Object.prototype`.

```JavaScript
typeof(Object.prototype); // is an object

Object.prototype.prototype === undefined; // true
Object.prototype.__proto__ === null; // true
```

So `Object.prototype` doesn't have a `prototype`, and it doesn't
"`__proto__`-inherit" from anything.  The buck stops here.

In JavaScript, each object `o` has a `__proto__` property that
points to the object that `o` **prototypely-inherits** from
(as opposed to "inherit" in the class-based sense).

So from here on, if `s.__proto__ === k` then we say `s` **proto-inherits** from `k`.  I use the term "proto-inherit" to distinguish from the Java-style, class-based, concept of inheritance.

Yes, `__proto__` is deprecated, but it works (for now) and is easier to think with.


We're going to start diagram out the relationship
between the various objects we're exploring in JavaScript.

![Object.prototype UML-like diagram](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJZIMM9zCjENTA9a-3J3tm3NwQV-KrRXFQzB5zyxwDC7Q7qPSXXrXncOHmTktqCMqdcAsw6xRAMbrKfj2FGI56gDbAwoBmqe6-ovF_ZS1tprzxwaSeHfUnqfBQ7sOSXRXbrHCA89AGQFA/s1600/d1.txt.png)

As described before, if you must think in classes, then making an object
in JavaScript is like writing a class and instantiating exactly one object
from it, so we'll draw objects in the style of UML classes.

i.e.

![UML-like class diagram example schema](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjjEss9UraMrJC7cwso34SN0A_SnETwAmxgnmLoYHQLanN68PI-Sd5Xr6KBPA1q-1HFp8H9dbkBgAUI7o6Expfhn5y4ePFGneu1sRJCoYwih4dP_NuyNeiGvysk2FqMc4lUszCaotE7dj4/s1600/d2.txt.png)


## Object function
But if `Object.prototype` is an object, what is `Object`?

```JavaScript
typeof(Object); // is a function.
```

Huh, but it had a `prototype` property before...
I guess functions are like objects and can have properties.

In fact, there is a circular relationship between
`Object` and `Object.prototype`:

```JavaScript
Object.prototype.constructor === Object; // true
```

Since functions can have properties, we'll draw them like objects
but tag them with "fn:"

![Circular relationship between fn Object and Object.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw2LI308pvxETX61mR7VYvqZH3mFJS71sn_ZLgoFPTygfm_jwi_LmzPXh-plk-1ZZVtPY18SIehfFFvLPtNoxFi2Ikfpuz6pET94i_1whyphenhyphenkjGLicaJFCLPw_YtxGg-BRImBw1aHKxdUak/s1600/d3.txt.png)

There's a general circular relationship between functions and prototype
objects as we'll soon see.


## Function function
Since `Object` is a function, what is `Function`?

```JavaScript
typeof(Function); // is also a function
```

Actually, `Function` is very much like `Object` with a
circular relationship:

```JavaScript
Function.prototype.constructor === Function; // true
```

But what is `Function.prototype`?

```JavaScript
typeof(Function.prototype); // is a function
```

So there's a general circular relationship between functions and prototype objects as well:

![Circular relationship between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiuPF29bpW2vp-gRCzPr42gT1c4CLaGu6uJCdv_FjqK6nbOUC2JqeVCeU7pxNOiUr8NnFBNGtNuJ8C8yHXvM3JnvzIC8hHsPjjU1M77zAjvML5AehBC0IQnsq_tNkpwrf8yAo445j8rOgQ/s1600/d4.txt.png)


## How do Function and Object relate?
Well we already know `Object` and `Function` are both functions.
Now observe where they proto-inherit from:

```JavaScript
Object.__proto__ === Function.prototype; // true
Function.__proto__ === Function.prototype; // true
```

Wasn't `Function.prototype` a function as well? Yes and no...

```JavaScript
typeof(Function.prototype); // recall that's a function
Function.prototype.__proto__ === Object.prototype; // true
```

![Circular relationship between fn Object and Object.prototype, and between fn Function and Function.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJhd17gDojdt-labL0wFRS4dTscyh6miYnTm0Ah8QFjNVEXmX-sB6pR-s5D40GI461_K9LvvIfZLbvWWyZDagKJrEfXwgAICl60XxcNyfXuMQU3iBux1BmkV49shIPFfd2f32QByp1DB4/s1600/d5.txt.png)

So the buck stops at `Object.prototype`, and `Function.prototype` is
a function but proto-inherits from `Object.prototype`.

`Object` and `Function` are both more straightforward:
both are functions and proto-inherits from `Function.prototype`.


## Literal objects and functions
Consider the following literal object and function:

```JavaScript
var x = {};
typeof(x); // is an object

var f = function(){};
typeof(f); // is a function
```

So what do they proto-inherit from?

```JavaScript
x.__proto__ === Object.prototype; // true
f.__proto__ === Function.prototype; // true
```

...they proto-inherit not from `Object` or `Function`, but from
`Object.prototype` or `Function.prototype`.

Remember the general circular relationship between functions and 
prototype objects? Well `x` is an object, so I suspect we won't
find it related circularly with its prototype object (if it has one)...

```JavaScript
x.prototype === undefined; // true
```

But `f` is a function, so let's see if it has a circular relationship
with its prototype object...

```JavaScript
typeof(f.prototype); // is an object
f.prototype.__proto__ === Object.prototype; // true
f.prototype.prototype === undefined; // true
f.prototype.constructor === f; // true, truly circular!
```

Thus we see the following relationship `x`, `f`, and the existing circular relationships between `Object`, `Function`, and their prototypes:

![Relationship between Object, Function, their prototypes, and object x and function f](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOr45lN9l-LPz9AMjmRLVkvxpfMP54xceqL9mpX7iQwbF-K-haYIV9IZVl5gLH1SjTIr1_iFyhLa39IsuCj0bjOGSVNOa_5DGRf5pNso4fjARMw1TVSCBsHcZ-Q2H_xiggqf3r9fD6Tcw/s1600/d6.txt.png)


## Let's start writing some "classes"
The goal here is to end up with a "super class" called `SuperKlass`, which will have as a "subclass" the class `Klass`.

```JavaScript
var SuperKlass = function(){}; // a constructor for our super "class".
typeof(SuperKlass.prototype); // is an object.

SuperKlass.__proto__ === Function.prototype; // true
SuperKlass.prototype.__proto__ === Object.prototype; // true

SuperKlass.prototype.constructor === SuperKlass; // true
```

So merely writing a function creates a circular relationship between
a function and an object:

![Relationship between Function.prototype and SuperKlass, and Object.prototype and SuperKlass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgT-GnQ0tXAQtfJOJ02r0Frb7m4lDKOOERu4z07wB4yUbkKL_-yizcD7uQmiPA5tGKiiC6MqJyfn3RawR2hkcFBEgKBRO_PnnjsyGXTo2Orw9V8x3I9VB_ywZ18BRr05pBxX01uA3RmUA/s1600/d7.txt.png)

We'll abbreviate our diagram of the `Function.prototype` and
`Object.prototype` objects.


```JavaScript
var Klass = function(){}; // a constructor for another "class"
```

As with the `SuperKlass` case above, we get this circular relationship:

![Relationship between Function.prototype and Klass, and Object.prototype and Klass.prototype.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiaQWqkD5vVpxmcuwgb_doNxXVcMqTpgnXapMgzO_jGH23z9klsJGGJt1l2sbeJNSeA_SPuDf1BR-EOFuyaaUfcHdoVjatBa9J-8yA6IEiYOFdyWfm-NyF1_93Op3q_eOyQ0kWtkqejt0M/s1600/d8.txt.png)

`Klass` and `SuperKlass` don't look like classes, but they would if we started writing some methods for them.  But we'll hold of on that until we get some class-based inheritance going on first as those two are currently unrelated to each other.


## Proto-inherit our way to writing "subclasses"
The above don't look like classes yet, but they will once
we make `Klass` inherit from `SuperKlass`.

```JavaScript
var oldKlassProto = Klass.prototype; // for later testing

Klass.prototype = Object.create(SuperKlass.prototype);

Klass.prototype === oldKlassProto; // false. It's really a new object!

Klass.prototype.__proto__ === SuperKlass.prototype; // true
Klass.prototype.constructor === SuperKlass; // true
```

The `Object.create` line of code basically did the following:
create a new object `o` that proto-inherits
from `SuperKlass.prototype`, then set `o.constructor` to
the `constructor` of `SuperKlass.prototype`, which is of course
just `SuperKlass` because of the circular relationship we saw above!

Then we set `Klass.prototype` to `o` resulting in
this relationship:

![Relationship between Klass, Klass.prototype, SuperKlass, SuperKlass.prototype, and Object and Function prototypes, after using Object.create.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqAQynhPfRyI9oNlAydARZg9KKtMl8YHVsoShd7rg0xgmW-1BltlZFFlFd80PHe7MWcQzV6DcuT6RD_W_3UwANabRmeBX2clW-6MUeOc-GPi9Z5wGO2euu0F9ZuCV5a6-qMzhhR95aTMo/s1600/d9.txt.png)

Notice the `Klass.prototype.constructor` no longer points back to
`Klass`, breaking the circular relationship between constructor functions
and prototypes we kept seeing above.  Let's repair that...


```JavaScript
Klass.prototype.constructor = Klass;
```

![Relationship after repairing Klass.prototype.constructor to point to Klass](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwx_vHpDKSwHatiEbKbPKT2ZDJQfz640hWDn9YX1Yb5BndPDqGa2W958oH5CA4rbcoB6cOtzImFMChc704YmcaqqORmBPlnU6sK0EiRi0B00Mpjh36KjCcOdPywCZ2tM3RbzrfXdrftkQ/s1600/d10.txt.png)

Now `Klass` is a subclass inheriting from `SuperKlass` --- inheriting,
not proto-inheriting.


## Instance method for our Klass and some new objects
Let's dynamically create a `SuperKlass` instance method:

```JavaScript
SuperKlass.prototype.hi = function(){return "super!"};
```

Notice where the method is created in the diagram and how it relates to `SuperKlass`, and `Klass`:

![Relationship after dynamically patching in a "hi" method in SuperKlass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjHAC3o2Katyy0MTOTeJXbp6JgtpON3wX3TJVYOc4MJ4Y3aEyau-7NghFiMpNy4nLQoPIXovxvPEZdBwsZUeJi8iW2fuhxduqNX4WFNa1msdLPVwMd3EgukzouQs4kCsphAW7RFHdeqZeM/s1600/d11.txt.png)

We keep making classes but never instance objects constructed
from those classes, so let's do that now:

```JavaScript
var sk = new SuperKlass();
var k = new Klass();

sk.prototype === undefined; // true
k.prototype === undefined; // true. They really are just objects

sk.__proto__ === SuperKlass.prototype; // true
k.__proto__ === Klass.prototype; // true
```

So `new F()` just makes a fresh object that proto-inherits from
`F.prototype`.  In fact, it also runs the `F()` constructor function
on that fresh object so to initialize it by doing whatever `F` does.

![Relationship between k and Klass, and sk and SuperKlass.](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieQZxagZ6zrIBovw4Sg5SE99IrwehtpIKv-M9g4A8Yl4FNXmo3UJV-xRLtweAOCy42N0jgRDycjGULR8bv1G_aKc9EI_GFJcfj5WQPdwd7UnA0Y-_0sKy4TcZZ_u4iEGJzGq0Gzg5oyGM/s1600/d12.txt.png)

## Polymorphism
"Polymorphism" here just means, if an object `k` has it, use it,
otherwise repeat looking for it with the object that `k` 
proto-inherits from (done recursively, again and again...).

```JavaScript
sk.hi(); // "super!"
```
...note that `sk` itself doesn't have a method `hi()`,
but `sk.__proto__` (a.k.a. `SuperKlass.prototype`) has it!

```JavaScript
k.hi(); // "super!" - polymorphic call to inherited method
```

`k` itself doesn't have `hi()`, but in this case,
`k.__proto__` (a.k.a. `Klass.prototype`) doesn't have it either!
But `k.__proto__.__proto__`  (a.k.a. `SuperKlass.prototype`)
does have it!

In effect we've got, in Java terms, an instance method `hi()`
defined in the `SuperKlass` class, and `Klass` inherits it being
a subclass.  So `k` is like an instance of the class `Klass`,
and `sk` is like an instance of the class `SuperKlass`...
even though JavaScript has no native concept of class or
class-based inheritance (not until ES6 anyway).

Let's write more methods, this time dynamically adding the `hi` method to `Klass.prototype`:

```JavaScript
Klass.prototype.hi = function(){return "klass!"};
```

Notice how this `hi` method relates to the `Klass.prototype` object, "overriding" the one proto-inherited from `SuperKlass.prototype`:

![Relationship after dynamically patching in a "hi" method in Klass.prototype](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiy61cgwO1v0tFIozlgQBaIW_ybFwdD-8kbDrerlsiCoTW5qgnyufyGaA7MMP2Cy6iWO6VthZlGtATpBe8dh1suG8jBsDf28I0lLnkyxb1f2YQnjbG9krKX8JrcvBQ2TscU21-bXugfpkg/s1600/d13.txt.png)

```JavaScript
sk.hi(); // "super!"
k.hi(); // "klass!" - polymorphic call to overriding method
```

...of course `k` itself doesn't have a method `hi()`,
but `k.__proto__` (a.k.a. `Klass.prototype`) this time does!

Although JavaScript has no native concept of class or class-based 
inheritance (not until ES6), it kind of half-heartedly does since
ES3 (JavaScript 1.4) via the `instanceof` operator which basically
just checks to see if a function's `prototype` is proto-inherited by,
or is proto-inherited proto-inherited by, or is proto-inherited 
proto-inherited proto-inherited by, ..., the given object.

```JavaScript
sk instanceof Klass; // false
sk instanceof SuperKlass; // true
```

The last line evaluates to `true` because `sk` proto-inherits from `SuperKlass.prototype`

```JavaScript
k instanceof Klass; // true
k instanceof SuperKlass; // also true!
```

The last line *also* evaluates to `true` because `k` proto-inherits proto-inherits `SuperKlass.prototype`

Just follow the proto-inheritance hierarchy!


## this and super
Let's write another subclass.

```JavaScript
var Klass2 = function(nm){
    // super(); in Java terms
    SuperKlass.call(this); // call superclass's constructor
                           // with `this` object
    this.name = nm;
};
Klass2.prototype = Object.create(SuperKlass.prototype);
Klass2.prototype.constructor = Klass2;

// Klass2 inherits from SuperKlass via usual proto-inheritance hierarchy:
Klass2.prototype.__proto__ === SuperKlass.prototype; // true


// make a `Klass2` instance
var k2 = new Klass2("Pat");
k2.hi(); // "super!" - polymorphic call to inherited method


// define a `Klass2` instance method
Klass2.prototype.hi = function(){return this.name};

sk.hi(); // "super!"
k.hi(); // "klass!"
k2.hi(); // "Pat"
```

More or less, `this` refers to the object the method is called on, but technically
it gets tricky as JavaScript's concept of a method is really in terms of functions
that are stored as properties on objects.  For details, see [MDN's JavaScript reference of this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).

Notice the dynamicism of JavaScript, where we added a new instance method to an existing class, and all existing instance objects of that class got to use the newly defined instance method.  No recompilation needed, unlike e.g. Java.

## References
It was noted that `__proto__` is deprecated.  It was a way of exposing to 
us the internal linkages between JavaScript's internal representation of 
objects.  The "proper" way now is through using the `getPrototypeOf` method.
See [MDN's reference on Object.prototype.\_\_proto\_\_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto).

A more in-depth explanation of JavaScript OOP can be found at MDN's 
reference on [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) or at [Introduction to Object-Oriented JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript).

A hugely more in-depth explanation with beautiful diagrams is available at
[JavaScript: the core](http://dmitrysoshnikov.com/ecmascript/javascript-the-core).
Incidentally, had I found that article first, I might never have written
this one...

...because I wrote this to help myself understand JavaScript's prototypal OOP system
by drawing diagrams and playing around with JavaScript in the Firefox Console.
Conceptually, it was so simple, but then when you actually program with it,
or when you try to use it in a more class-based manner, it can get confusing.

All diagrams originally drawn with [ASCII Flow](http://asciiflow.com).  Diagrams turned into pretty PNG images using [Shaape](https://github.com/christiangoltz/shaape).

2015-03-27

Lynda.com for learning computing science as high school students: a review

Recently, I had a chance to spend some time reviewing Lynda.com's offerings on various computing science topics.  The review here is geared towards using Lynda.com with high school students as the target audience.  I thought I'd share a few observations.

Lynda.com is ok for what it is, that is, as a quick introduction to topics for what seems to be its intended audience of busy professionals working in the field.  At least I think that's their target audience.

For high school students, however, especially for beginner, intermediate, or even middle to lower level advanced high school students, Lynda.com's offerings for computing science topics are simply inadequate, missing curricular connections, and uses pedagogy ill-fitting for students in the high school age range.  That's not really a bad thing for Lynda.com, as I don't think high school students are their target audience at all.

2014-08-15

Java has deep expression problem for beginning students

There are many problems with Java as the first programming language to teach students if we wish to provide the most effective learning experience.  I've written on this in Learn Python instead of Java as your first language in the past even.  So what now?

Newbie, meet the Expression Problem

Stuart Sierra provides a very lucid explanation of the Expression Problem, a classic problem in software programming, in Solving the Expression Problem with Clojure 1.2.  Needless to say, Clojure provides a very clean solution.

Java, however, is a quagmire and requires some heavy OOP software engineering concepts to solve the Expression Problem.  One wouldn't ordinarily think this has anything to do with beginning students just learning to program though, but it does, and here's how.

Imagine our beginning student, "Sam", starts to learn Java and eventually starts to write a classic game of asteroids.  Sam plugs away and gets a decent game of a single player ship shooting lasers at one kind of asteroids to begin working.  Not bad!  But Sam wants to do more.  Sam wants to not just have one kind of (big) asteroids, he also wants to have small asteroids to shoot at.

Alright, so Sam begins to modify the BigAsteroids class to also be able to represent a smaller sized kind of asteroids.  The teacher catches wind of this and tells Sam, "no, that's not good", and that Sam needs to use OOP principles to write a different class for SmallAsteroids.

Now most students would say "why, Mr. Teach", my way works.  But Sam is a good student and does as he's told.

So Sam goes and creates a second class for SmallAsteroids.  Except his program was built presuming that the only things to draw, to shoot lasers at, and to move around, were BigAsteroids.  None of those methods he wrote to draw, to shoot lasers at, and to move around BigAsteroids work for SmallAsteroids.  hmm...  Welcome to the Expression Problem, Sam.

2012-01-01

Web Mobile App Development Tools and Libraries

Here's some tools and libraries that look interesting for web development, mobile App development, etc.

To begin, Firefox and Chrome, of course, are the browsers of choice for a web developer.

Tools for Firefox

Firefox has tons of tools for web developers! Take special note of:
  1. Firebug,
  2. Console²,
  3. DOM Inspector,
  4. FoxGuide,
  5. HTML Validator,
  6. JSView,
  7. LiveReload,
  8. PageSpeed,
  9. Phoenix,
  10. SQLite Manager,
  11. Web Developer.
  12. ColorZilla

If using Firebug, then also take special note of Acebug, FireRainbow.

Tools for Chrome

Chrome is younger and has less tools, but many web developers prefer Chrome over Firefox.  And there are definitely tools:
  1. Google Chrome Developer Tools
  2. Web Developer
  3. Firebug Lite
  4. Validity
  5. ColorZilla 
  6. Color Generator
  7. Eye Dropper

JavaScript Validator

When programming in JavaScript, you must use JSLint to validate that the JavaScript you wrote conforms to modern recommended idioms.

You can run JSLint on the command line locally if the JSLint program is set up correctly based on the JSLint source files. But then a JavaScript interpreter outside of the browser is required, such as node.js, Rhino, or spidermonkey.  Another, more convenient, possibility is to use the jslint4java wrapper program.


Libraries

dust.js has been selected by LinkedIn recently as their templating engine to unify the way web pages designed in HTML and CSS gets filled with data generated by other server based programs written in various languages including Java, Grails, and JRuby.  It is free and open source (looks like MIT license)

PhoneGap is a free and open source (Apache License) library for writing cross-mobile-platform HTML5 app to access technologies native to the mobile platform (vs. programs being stuck in the browser).

For building gesture/touch-enabled UI for cross-mobile-platform Apps, there is jQuery Mobile, which is a very young project still, and is free and open source: dual licensed under MIT and GPL2.  There is also Sencha Touch, a more mature library that is free and open source, cross-licensed under GPL3, a modified GPL3, a free (as in beer) commercial software license, and a paid commercial OEM license.

You might also need a library to add MVC or MVVM structure to your App.  For that, consider Backbone.js (MVC) or Knockout.js (MVVM).

For everything else, there's jQuery.

See also:
  1. Building Large-Scale jQuery Applications
  2. Tools For jQuery Application Architecture – The Printable Chart

2011-12-31

Resources for Learning Web Development (JavaScript, jQuery)

Assuming you have some working knowledge of HTML and CSS, then learning to program behaviours into web pages requires learning JavaScript, and here's resources I've looked into to help you learn JavaScript programming:

eBooks and paper Books
By "books", I mean "Bound Optimally Organized Knowledge". It's organized for structured learning and completeness.

Books I've looked into (literally) and would give at least a 4 out of 5 stars for:
Books that look promising based on the "cover" only:
  1. jQuery Fundamentals
  2. Web Development Recipes 
  3. Eloquent JavaScript: A Modern Introduction to Programming
  4. MDN: JavaScript Guide
Interactive Tutorials
Tutorials are organized for structured learning, often in a hands-on manner, but usually leaves gaps in knowledge.  Interactive tutorials have a turn-based prompting mechanics to it.