Monday, May 23, 2011

Scoping in javascript

In order to learn a language thoroughly it is essential to understand how the language's scoping rules are defined. In this blog I would like to summarize how javascript scoping works to solidify my understanding. I will go over what scoping is, how it works in javascript, and the different types of scopes in javascript.

What is scope?

From wikipedia:
In computer programming, scope is an enclosing context where values and expressions are associated.

Scoping allows you to organize and enclose your variables and expressions in a certain environment. In most cases scope is used to encapsulate and hide information from other parts of the program. This keeps your application safe from modification by other people. For instance in jQuery or other javascript libraries the library authors done want people to be able to modify variables internal to the library so they enclose their library in a scope.

How is javascript scoped?

Javscript is said to have lexical scope. This is also known as static scoping because you are able to resolve the scope of variables by parsing the program text. In javascript this is done by analyzing the nesting of function blocks. As seen in this example.

Also note that if you define a variable in a nested scope that has the same name as an outer scope the variable will reference in the inner most scope. As seen here.


Whats with the var?

The var keyword is used to say this variable belongs to the current scope. Without using this keyword in a function the variable will be put into the global scope. To see this in action see the following code sample.

As you can see when not using the var keyword your variables will "bleed" into the global scope. This is one of the biggest issues when debugging javascript. Always var your variables to avoid pulling your hair out.

Where did the global scope come from?

By default every javascript program will execute in a global context or scope. For most javascript this is the window object because the javascript is executing in a browser. To show how this works lets modify the previous examples a bit.
As you can see when you do not define a variable with var then your variable will end up in the global scope which can then be referenced outside of your function with or without referencing the name of the global scope.

There are other types of scope in javascript....

When we use the var keyword we are actually putting variables in the local scope. This scope is only accessible to itself and nested functions. See this code sample:

As you can see the variable created with the var keyword is not accessible outside of the function. On the other hand you can use the this keyword. The this keyword is used to reference the current execution context and will be available as a public variable as seen here.

However one of the most important features of the this keyword is the fact that you can change the current execution context. The are 3 ways to change the current execution context: call, apply, bind. These are often used to change execution context when executing a callback. Take a look at the following:
As you can see if you do not use call,apply or bind then this in the callback will not reference the button firing the event. To make this work you can do the following. Using call you can pass in this as the first parameter and then a list of the arguments to the function. This will set this of the callback function to the this that is passed into the call function.

Alternatively you could use apply. The only difference is the arguments that are passed to the function are defined as an array. As seen here: . Lastly there is bind which returns a copy of the function with this and the arguments bound which you can then call later.

With bind you have to be careful because it is only implemented in the new versions of javascript. The final scope you need worry about in javascript is block level scope. This creates a new scope in if and for blocks by using the let keyword. See the following code sample. As you can see the code creates a new variable x using let which makes it local to that if block. Be careful when using this becuase it is only available in newer firefox versions.

In this article we examined how javascript handles scoping. We learned that javascript is lexically or statically scoped which means we can figure out the scoping rules by looking at the nesting of the functions. We learned that when no scope is given when creating a variable then it will be put in the global scope, usually this is very bad. We learned that we can create local variables to the current scope by using the var keyword. We learned that when using this it is referencing the current scope, and can also be changed by calling call,apply, and bind. Finally we learned that we can create block level scoping by using the let keyword in some browsers. Obviously scoping is a very important language topic and is essential knowledge before using a language.

Tuesday, March 8, 2011

Important Concepts in Javascript: Prototypes

Another common answer to my question on Quora about important javascript is Prototypes. I have been researching javascript prototypes for a few days now and I think I have come up with a pretty good summary. First lets start off with the wikipedia definition:
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.
Delegation

In the final sentence it says that Delegation is the language feature the supports prototypes. If there is no delegation there are no prototypes. So lets first understand what Delegation is from wikipedia
  • Most commonly, it refers to a programming language feature making use of the method lookup rules for dispatching so-called self-calls as defined by Lieberman in his 1986 paper "Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems". Delegation as a language feature supports the prototype-based programming model.
  • In its original usage, delegation refers to one object relying upon another to provide a specified set of functionalities. In research, this is often referred to as consultation or as aggregation in modeling.
In short Delegation allows objects in a language to lookup methods that are undefined on its self in another object. In javascript this object is called a Prototype object. The rules that govern how this method lookup works is called the Prototype Chain. More on this later.

The .prototype Property

The .prototype property contains the Prototype object for any given object. To demonstrate the .prototype property consider the following code example:

As you can see the prototype is a normal object and when calling a method undefined on the original object it will try to look up the method on its prototype via Delegation.

The .__proto__ Property and Object.getPrototypeOf

Many newer browsers have the non standard property __proto___ and in the ECMAScript5 spec there is a new function on Object called getPrototypeOf. To see why these are useful take a look at this code:

Basically what happens here is when you create an object based on the Foo object constructor but then change Foo's prototype after instantiation it takes a snapshot of Foo's prototype at the time of object instantiation. __proto__ and Object.getPrototypeOf get the prototype object of the instance of the object when the object is instantiated. To change the internal Prototype of an object you must use __proto__ or getPrototypeOf.

The prototype chain

In javascript there a rules on how javascript performs a lookup for the methods on an object and its prototypes. This is called the prototype chain. Here is a code snippet to demonstrate how the prototype chain works.


As you can see this script demonstrates that first the method is looked up on the object itself, then on the objects constructors prototype and finally on the objects internal prototype.

Inheritance

Prototypes in javascript are useful because you can share prototypes (and their methods) between objects. Using prototypes in this manner is used to emulate inheritance like you would see in traditional class based programming languages. Here is an example of how you can use prototypes to emulate inheritance:
As you can see using the prototype allows us to share the eat method between the different types of Animals. An added benefit of using this is that all Animal instances will share the same eat method cutting down on memory usage.

Hopfully this has helped you gain a better understanding of how prototypes work and also how to implement prototypes in your code in an object oriented manner.

Tuesday, February 22, 2011

Controlling Big, Mean, Devices.....With Javascript!

It amazing how far from the browser javascript has come with server side technologies like NodeJS. Now we can even control things outside of the browser or the server...How about electricity? Using an arduino it is now possible to control things with javascript outside of your computer. To do this you will need the following things:

  1. A Relay Control Board:
    http://www.sparkfun.com/tutorials/119

    http://www.instructables.com/id/Arduino-Controlled-Relay-Box/

  2. An Arduino http://arduino.cc/en/Main/ArduinoBoardUno

  3. Knowlege of javascript and git.

  4. A working install of NodeJS NPM and the Arduino software.



Yeah, I know this is alot of requirements but you gotta pay to play. I am not going to go over these things either, search the web and you can find much more info then I could type in this blog post, and plus I want to get to the code!

First thing is first. I am going to make a new folder to hold all my js code lets call it "PowerSwitch". I am going to create a directory "deps" under "PowerSwitch" cd into the "deps" directory then clone the node-arduino project. This is a project created by the guys at uxebu to control an Arduino over a serial port via NodeJS.

git clone https://github.com/tobeytailor/node-arduino.git

For whatever reason (I am not sure) I cannot get the "node-serialport" submodule to init. When I do:

git submodule init

In the node-arduino folder I get:

No submodule mapping found in .gitmodules for path 'deps/node-serialport'

No bother though we can install node-serialport from NPM which is even easier anyways. We will update the reference in code later.

npm install serialport

Now that we have the node-arduino library we have to upload the Arduino code to the arduino. Ok. Ok. I lied this is not ALL javascript but all you should need to do is upload this processing script to the Arduino one time. This script basically accepts commands over the serial port. You can view more detailed on this process here http://arduino.cc/en/Guide/HomePage. Overall here are the steps:

  1. Plug in Arduino to your computer.

  2. Start the Arduino software

  3. copy the contents the file in PowerSwitch/src/node.pde to the editor in the Arduino software

  4. Press the upload button.



You should see "Done uploading" if everything was successful. Now its time for some javascript code. First thing we will need to do is update arduino.js in PowerSwitch/deps/node-arduino/lib. Change this:

to:
. This will change the arduino library to reference the serialport library we installed via NPM instead of the library that was installed as a submodule relative the node-arduino library. Next lets create a file called server.js and put copy this code into the file.

This code depends on express. If you dont have express install it.

npm install express

Now create a new folder in PowerSwitch called public and put this index.html file there



Now run server.js

node server.js

Now hook your relay control board to your arduino. I used pin 12. Now plug in your appliance to relay controlled outlet. Then navigate to http://localhost:3000 and you should see a button click the button and the power should turn on. click it again and the power should turn off. Now I noticed a few issues with the node-arduino library. If it does not work the first time just stop and start the app a few times and you should eventually get it work. I have forked the project and I am hoping to get all the issues fixed.

Here is a video of it in action.

Monday, February 21, 2011

Important Concepts in Javascript: Closures

The other day I asked "What are the most important javascript concepts to know for a job interview?". The most common answer was Closures so I figured I would google it. From wikipedia:
In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

I know, wha? I think after a few hours on wikipedia I think I finally came up with a code snippet that illustrates that statement.

Still confused? I think mozilla explained it the best:
A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

and
A closure lets you associate some data (the environment) with a function that operates on that data.

Ok so why do I care?
Well if you have ever done any web programming in javascript you have probably been using this for years without even knowing it. Lets take a look at binding a click event in jQuery:

Also if you have ever created a javascript objects using the module pattern:


Closures are something that javascript programmers use everyday. To most it comes second nature and you may not even have to think about using them. The simplest definition I can think of is: A closure is when you return a function from within a function and the inner function has access to the environment of the outer function(s) OR when you pass in a function as an argument when creating a callback. I hope I helped clarify this for some people. Please leave a comment if you have a suggestion to improve this article. To find more info check out:

https://developer.mozilla.org/en/JavaScript/Guide/Closures
http://blog.morrisjohns.com/javascript_closures_for_dummies.html

Friday, July 23, 2010

Java-WebSocket, CFWebsocket, CFWebsocketChat

I have just updated TooTallNate's Java-Websocket to be compliant with Draft 76 of the websocket spec. I have also updated my CFWebsocket to also be Draft 76 compliant. Finally I have put up my WebSocketChat. All the Repos can be found here

GitHub

The chat can be found here:

Chat

After you choose any user name you like click the Default room on the right to start chatting! Let me know what you think!

Wednesday, July 7, 2010

CFWebsocket

With the coldfusion community usually being on the cutting edge I was surprised to see that no one had implemented a websocket gateway for coldfusion (that I had seen). So I decided to build a custom coldfusion gateway so people can use coldfusion with websockets. My implementation is based off of TooTallNate's java websocket. http://github.com/TooTallNate/Java-WebSocket . You can access the jar witch contains the .class files and .java files here.

To Use

1. Download JAR, place in coldfusion classpath and restart server.
2. Download the config file, websocket.cfg, from here to serverroot/gateway/config/ . Optionally open file and change port the default is set to 88.
3. Add new gateway type the setup should look like this.
4. Create a new CFC like the one here.
5. Add new gateway instance that should look like
this.
Note: set the CFC path to the cfc you created in step 4.

Your gateway should now be setup for use. The CFEVENT struct in the gateway has a connection attribute which is the websocket connection object which has a .send() method to send data back to the client. In the onclientmessage function of the gateway there is also a message attribute in the CFEVENT struct that contains the message sent from the client. I should soon be uploading a chat application using this gateway to show how an application could be made. Also I have not load tested this or used it in a production environment so use at your own risk!

Tuesday, June 1, 2010

Addresses

If your looking for the wedding invitation address entry form click here.