Thursday, April 18, 2013

Notes on JavaScript

JavaScript Prototypes - "Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype." From JavaScript: The Good Parts, "In classical languages, objects are instances of classes, and a class can inherit from another class.  JavaScript is a prototypical language, which means that objects inherit directly from other objects."   From page 50, "In a purely prototypical pattern, we dispense with classes.  We focus instead on the objects.  Prototypical inheritance is conceptually simpler than classical inheritance: a new object can inherit the properties  of an old object."  Article by Crockford on Prototypical Inheritance


Lexical vs Dynamic Scope -  "In lexical scoping (or lexical scope; also called static scoping or static scope), if a variable name's scope is a certain function, then its scope is the program text of the function definition: within that text, the variable name exists, and is bound to the variable's value, but outside that text, the variable name does not exist. By contrast, in dynamic scoping (or dynamic scope), if a variable name's scope is a certain function, then its scope is the time-period during which the function is executing: while the function is running, the variable name exists, and is bound to its variable, but after the function returns, the variable name does not exist. http://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping.  Perhaps lexical scope can be roughly summarized as "scope as written" while dynamic scope is "scope as run."



Quote about JavaScript: "Many of JavaScript's featurs were borrowed from other languages.  The syntax came from Java, functions came from Scheme, and prototypal inheritance came from Self.  JavaScript's Regular Expression feature was borrowed from Perl." JS: TGP pg 65


Function Scope vs. Block Scope
"Most of the commonly used programming languages offer a way to create a local variable in a function: a variable that, in some sense, disappears when the function returns... Many languages take function scope slightly further, allowing variables to be made local to just part of a function; rather than having the entire function as its scope, a variable might have block scope, meaning that it's scoped to just a single block of statements."  JavaScript has function scope, not block scope.

Suggestion for JavaScript Global Variables
"I use a single global variable to contain an application or library.  Every object has its own namespace, so it is easy to use objects to organize my code." JS:TGP pg 97