Code in languages like Java or C is compiled to byte or machine code. When your app runs, it's taking instructions from code and operating on data.
Dynamic Languages, like JavaScript are rather different. Instead of a strong separation between code and data, your application is built one statement at a time. You are effectively programming your program.
For example, what happens when a script tag like <script type='text/javascript' src='myapp.js'></script> loads the following code?
var JS = {};
JS.says = function(message){
alert('JavaScript Says "'+message+"'")
};
JS.says("Hello World");After making an HTTP request for the contents of myapp.js, it passes the contents to the browser's JavaScript engine. The JavaScript engine tokenizes, and parses the code. Then it runs each statement, one at a time, building your program in memory. Lets look at this visually:
In JavaScript, there are two types of data:
- primitives like "1", 1, true, null, undefined
- objects like {}, [], function(){}, /reg/, new Foo
A primitive
A pointer is a placeholder that points to another location in memory. It's a reference to another object. In JavaScript, there are two
It's all about how a function is called. A function is called in one of 4 ways:
func() // 'this' is the window
object.func() // 'this' is object
func.call(object, arg1, arg2) // 'this' is object
func.apply(object, args ) // 'this' is object
NOTHING else matters. A function does not care where it was created. There are no 'methods' in JavaScript.
// animal.speak === DOT(animal,'speak')
DOT = function(obj, prop){
if( obj.hasOwnProperty( prop ) ){
return obj[prop]
} else if( obj.hasOwnProperty('__proto__') ) {
return DOT(obj.__proto__, prop )
}
}// new Foo('bar') === NEW(FOO,['bar'])
NEW = function(Constructor, args){
// create object
var o = {};
// assign proto
o.__proto__ = Constructor.prototype
// run Constructor
Constructor.apply(o, args)
// return o
return o;
}When a function is called, a call-object is created. It keeps a list of references to the arguments passed to the function and variables created in the function.