JavaScript Object Inheritance Part 2

Previous JavaScript Object tutorial: link

Improving JavaScript Inheritance

In the last JavaScript tutorial (link above) we built simple hierarchy or chain from Car object to volvo object. To find a property (or key/value pair) JavaScript checks local properties in the volvo object and, failing that, moves to the Car object. If not found at all, then JavaScript returns undefined. So, just remember that local properties always override inherited ones.

And now to the downside… JavaScript offers very few ways of controlling the adding, changing, and removing object properties. However, lets see what we can do to help.

Creating a JavaScript ‘Template’ Object

Simple example of JavaScript object inheritance
Simple example of object inheritance

 

 

 

 

 

 

 

 

 

Re-writing JavaScript code

Create a JavaScript object with local properties

 

 

This time, I used Object.create to create the Car object linked to an empty object ({}).  And, importantly, we can declare four Car properties as well – tax (value) and setValue, getValue, and toString as functions. So, all objects will share a common tax setting and have access to three helper functions. Also, you’ll notice that I did not declare brand and model in the Car object, as we need those as local to individual cars only.

Property attributes

The power of Object.create comes from assigning attributes. In our example, tax is read-only (writeable: false), while configurable: false means ‘cannot be deleted’. So tax has the same fixed value for all cars.

Next comes three helper functions available to all cars. setValue() restricts updating to local properties, while getValue() to properties that exist. Both throw errors, if these conditions are not met. You may see that as drastic and want change to a different response. Finally toString() formats and returns a car description. Also notice the use of back-ticks (`) to enable template literals with ${} and use of this to identify the calling object.

Coming Up Next…

In the next blog we shall examine how to create the car object, volvo, add another property, set property values, and call a property function. Stay tuned.

JavaScript Objects – Simple Inheritance

JavaScript Objects Continued…

Previous JavaScript article: Objects Introduction.

In this article let’s see how to use JavaScript inheritance though a simple hierarchy or chain of objects. As a reminder, JavaScript objects are simply collections of key/value pairs, where the keys are unquoted strings, such as brand and model, year, and servicing. Values can be simple like numbers and booleans or complex like arrays or other objects. These key/value pairs are often called properties in objects.

Simple Object Inheritance

Simple example of object inheritance

 

 

 

 

 

 

 

 

 

 

In the above example we create a new object (lines 3 to 9) with three properties (key/value pairs). The capital first letter of the object name is to show that this will be a template for other objects.  Then we use the Object.create function (line 12) to create a new empty object with a link to the Car object. So JavaScript now has a search path to find properties, as demonstrated in line 13. The property brand does not exist in the volvo object, so JavaScript uses the link to check the Car object for a local brand property and with success. And the same applies to the tax property (line 14).

Creating a local property

However the volvo object needs its own property value for brand. We do that in line 17 with the assignment command. An assignment will do one of two things: (1) if the local property is missing then the assignment will create one; or (2) if it exists, then JavaScript will simply modify its value. Effectively, the new volvo.brand property now blocks the Car.brand property.

As a general principle, create shared properties at the top of the chain (e.g Car) and individual properties at the bottom (e.g. volvo), where JavaScript starts searching.

Finally, the last line demonstrates three possible search outcomes: (1) use of local property; (2) use of shared property (higher up hierarchy), if no local property; and (3) unable to find property in the whole search chain (undefined).

In the next article we shall look at better ways of creating a new object, adding properties, and modifying property values. Alex McCullie

JavaScript Objects – Pragmatic Intro Part 1

Object-oriented view
How programming see software solutions (Image courtesy of phanlop88 at FreeDigitalPhotos.net)

 

 

 

 

 

 

 

 

 

Why Objects?

Seeing the world as connected objects is how most programmers build software. Major programming languages today, including JavaScript, support this object-oriented approach to creating software. This article is the first in a practical series showing how you can use JavaScript objects to build robust, maintainable software. We shall see how objects hold state (knowledge about themselves through variables) and behaviors (special routines with methods or functions). Also later we shall examine how JavaScript enables the reuse of code through classes.

Sometimes JavaScript programmers want to group common routines and data together. For example, you may use special financial processing. Alternatively, you have some routines startup values and procedures. Single occurrence objects are great for this and add the benefit of avoiding name clashes with other libraries of code. In JavaScript we use Object Literals.

Defining an Object Literal

Lets work though some JavaScript that declares and uses object literals.

Defining an object literal

 

 

 

 

 

 

 

 

 

 

An object literal is defined between curly braces (lines 7 and 25 above). Properties are name/value pairs with names as unquoted strings, followed by colons. Values can be any JavaScript values including function definitions. Commas separate properties.

Notice the use of this to access a property of the object from within the object definition. For example, this.street accesses the street property of the object. Line 26 shows one way of accessing an object property. An alternative way is aHouse[‘suburb’]. Also lines 17 and 26 use back quotes (`) to use template literals, the ability to embed variable references into strings without using concatenation (+).

Modifying An Object Literal

We can also change an object literal during the running of the software.

Modifying an object literal

 

 

 

 

 

 

Lines 29 and 30 show two ways of modifying a property value. In line 33 we add a new property, lastInspection, by referring to property that does not exist. One is automatically created. And, finally, use the key word, delete, to a property (line 36). No error occurs if that property does not in fact exist.

Final Words

Here are some useful examples, including checking if a property actually exists.

Object literal – others

 

 

 

 

You can check for a property using hasOwnProperty as shown in lines 39 and 40. Then there are three examples of accessing object data. Object literals are a great way of organizing code that fulfill similar purposes  and avoiding variable name.

I have included the source file listed below for download. All routines are embedded in a self-executing anonymous function (IIFE) to avoid declaring global variables.

by Alex McCullie source file: oop_object_literal

Javascript for Programmers

Javascript is one of the need-to-know programming languages – once much-maligned but now begrudgingly respected as fully matured, worthy of knowing and using.

Latest Versions

The latest versions of Javascript, ECMAScript 6 (or 2015) and ECMAScript 7 (or 2016), offer features that improve Javascript as a modern language. Unfortunately these versions are only partially supported by browsers. However, libraries like Babel come to the rescue by converting your code backwards to fully supported 2011 version. It sounds messy but can be turned into a simple process. I use nodejs with Babel and Visual Studio Code and ESLint to work in Javascript, as I do with C++, Java, and C#.

Two Great New Features

My first choice and that of any others is the new Javascript arrow function. So compare tradition declaration with the newer arrow function below. As well as being much cleaner (less noisy) the arrow functions offer other advantages, especially for functional-style programming. Check out the link above for more benefits. By the way, => is often called a ‘fat arrow’.

Compare new and old style JS functions

This image introduces another great Javascript improvement – const and let for declarations. Seriously don’t use var. const forces you to declare and assign an immutable variable while let (mutable) offers better scoping and helps with the dreaded Javascript hoisting issues. I mention a const caveat later.

Use newer style JS declarations

Want More Than Javascript?

Do you want more than modern Javascript? There are many libraries and applications to help, and most are free and open source. The following projects caught my interest, even though I am not endorsing them. Your choice depends on needs and experience. Just stay clear of projects that depend on one developer who may lose interest. The project can quickly die as many have. Also be wary of those not updated for a few years. Check the GitHub source dates for last updates. Here are two comprehensive lists to start your search:

https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js
https://www.slant.co/topics/101/~best-languages-that-compile-to-javascript

Javascript With Extras

This is a popular category with offerings like CoffeeScript (and spin-offs) and TypeScript from Microsoft. You still work with Javascript, but they add extra features like type declarations.

JS++ enhanced Javascript

JS++ offers full support for compile time and run time type checking. As well as offering impressive enhancements, JS++ works well with existing libraries and code. I used Ramda, functional programming library, with no hassles. The quality and depth of JS++ seem to address many concerns for developing large scale Javascript applications. Combined with good documentation makes JS++ worth a look.

js++ Integration with File Explorer

Finally, another great feature is its integration with Windows, my development platform, and File Explorer. This is great for quick compile-time checking, even though the command line is still available.

 

So here is an example of conversion. I declared a function and its parameters as Int (integer) types. You notice it is JS 2011 standard that is widely accepted.

 

 

Functional Programming and Ramda

Javascript is not a dedicated functional programming language like Clojure, Haskell, and O’Caml. But Javascript offers features to make functional applications, if you have the desire and discipline. For me functional programming offers simpler, more robust code that is easier to test before deployment. However I suggest using a good Javascript functional library to help. This list is a good starting point.

https://www.slant.co/topics/408/~best-libraries-for-functional-programming-on-node-js

Ramda is a popular Javascript functional library offering simplicity and good documentation. However you need to spend time learning about functional programming and, how it differs from object orientation. There are plenty of on line resources as well many good books, including this one from Apress that helped me, Beginning Functional JavaScript. The author steps through building your own library – a great way for understanding.

Here are two different ways of creating a new list from an existing one. Simply adding one to every value. The imperative way is to loop explicitly through a list with temporary variables. By contrast, in functional programming we code a rule for the map function to complete the process. We do not care how that is done. You will notice the Ramda library is treated as an object and is referenced by R., such as R.map(. A final remark about this code. I could have declared newList as a const, and the code would still work. const blocks you from reassigning a variable name to a new list, in this case. If you want stricter immutability, then check out https://github.com/facebook/immutable-js.

 

From Other Lingos?

Many developers are comfortable with other languages like Python, Ruby, Clojure, and Scala. They want to reuse existing code in Javascript. My earlier links listed many projects of language converters to Javascript for you to explore. Here are some that caught my attention.

Pythonic Takes

Transcrypt uses a Python coding to produce 2011 or 2015 Javascript code. Its aim generate efficient Javascript code with access to the full Javascript ecosystem. So it supports the easy inclusion of existing Javascript code but little support for existing Python libraries. However the project does include part of the NumPy library to use.

Everything about the website, documentation, and software demonstrates that this is a serious effort to bring Python advantages to Javascript. Here is a quote for the Transcrypt website of the Python features you retain.

Multiple inheritance, recursive tuple assignment, multi-loop nested list comprehensions, LHS and RHS extended slices, assignment of bound functions, lambdas, named, default, *args and **kwargs parameters, properties, optional operator overloading, iterators, generators, async/await, selective exception handling and a hierarchical module system are just a few of its characteristics that make this clear. Transcrypt is parsed by CPython’s AST module, so no surprises there.

The good news for debugging is a simple correspondence between the Python code and generate Javascript as the images below show. I took some existing blockchain coding (simplified) and show the generated Javascript (see blow). Incidentally, Transcrypt generates multi-level source maps for debugging.

Python code followed by generate Javascript. Uses Javascript SHA256 library!

 

Lisp, Closure, and Parentheses

Finally let’s look at a project that generates Javascript from a Lisp/Clojure style language, RamdaScript. RamdaScript appears to be a small project that would appeal to Ramda library users. It does to me.

RamdaScript uses a Lisp style coding with about six commands combined with Ramda functions. The software generates clean code that references the Ramda library. You can embed Javascript at any time between #….#.

A really cool thing about RamdaScript in the online compiler at https://yosbelms.github.io/ramdascript/. As you type completed expressions in RamdaScript the equivalent Javascript appears on the right side. This is a great way of learning the basics of a Lisp style language, like Clojure, as well as The Ramda library. Or you can simply paste the generated code into your Javascript application.

 

 

 

 

 

 

Other Javascript Compilers

There are other good compilers for Javascript from popular languages. ClojureJS implements the Clojure language, not surprisingly. RapydScript is an interesting alternative for Python users, while Ruby users can look at Opal. There are many other projects that are also worthy of exploring. Google your language and Javascript to see what links display.

Closing Remarks

Javascript is truly a full member of today’s language pantheon despite quirks that continue. More and more programmers are using Javascript for full-stack development of significant web applications. You can find many well written and supported libraries that show Javascript has come of age. It is no longer a toy scripting programming language to make glossier websites.

Rosetta Code – Comparing Programming Languages via Common Tasks

So what is Rosetta Code? You know at least one programming language, say Python, and you come across another like Ring (Ring at Source Forge). In cases like this you want to compare the “how to” of a familiar task, and that’s exactly what Rosetta Code does for you.

What is Rosetta Stone?

Rosetta Code lists many programming tasks – some common and others much rarer. You can pick one that’s familiar and then scroll through looking at different coding solutions for each language. These samples are submitted by users. Each language is linked to a simple page describing the language and usually with an official home page. I should note that not all languages are represented on each task (typically the most common only).

Rosetta Stone for Learning

As well as simply reading the code, I use these samples as a great way of learning a new language.  Here are the images of comparing Python and Ring code samples in reading a text file line by line.

Criticism

My only criticism is the inconvenience of display coding samples of one language only. You can list the languages to pick one. That’s great so far. You can then choose a task for that language, but Rosetta Stone then displays all solutions from other languages as well. I’d prefer an option of displaying all solutions for one language only. This would be great for learning. If some one knows how, please tell.

In future blogs I’ll use Rosetta Code regularly to explore alternate languages: it’s a fabulous resource. In the meantime have fun exploring this wonderful site.

Alex

Rosetta - display tasks menu
1. Display tasks menu
Rosetta - finding a task
2. Find a task
Rosetta - displaying Python code
3. Display Python code
Rosetta - displaying Ring code
4. Display Ring Code