julian on javascript: functions julian m bucknall, cto

Post on 17-Jan-2016

241 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Julian on JavaScript: Functions

Julian M Bucknall, CTO

Functions are objects− Is an encapsulation of some code− Can have properties and methods of it’s

own− Can appear as a parameter, can be

returned from another function− Like all objects, functions are passed by

reference not value

Defining a function− Two main ways:

− Function literal− var f = function(arguments) { … };− var f = function optName(arguments) { … };

− Function statement− function f(arguments) { … }

Return value?− All functions return something

− There is no void type− “return;” will return undefined− If no return statement

− Function returns undefined− Unless it’s a constructor, called via new

Invocation− When invoked, all functions get two extra

variables− this

− <evil laugh>− arguments

− The parameter values of the call as an array-like object

Invocation patterns− Method− Function− Constructor− “apply”

Method invocation− Defined as a method on an object− Called via that object− this points to the object containing the

method− Like C#, really

Function invocation− Defined as a global function

− Or, defined as an internal function− Called without reference to an object− this points to the Global Object

− Catches everyone out

The Global Object− Has no name− Is where all unowned variables (primitives,

objects, functions) end up as public properties− are visible to all code!

− Browser sets up a special property called window to point to the Global Object − (window is a property of the Global Object)

Constructor invocation− Defined as normal function− Convention: Name has initial uppercase

letter− Called with new keyword− this points to object being constructed

− constructor property already set− Object constructed is returned by default

− No need for return statement

“apply” invocation− Defined however you want− Called via the function’s apply method

− Alternately: use the call method− You get to define the this object

Scope− Scope in JavaScript is by function

− NOT braces as in C# − No block scope here

− The this object stays with the outer function, inner functions get their own this (usually the Global Object)− Watch out for callbacks

Scope 2− A variable declared in a function is visible

throughout the function− Even before it’s lexically defined

Closures− The “yay!” to scope’s “ow!”

Thank YouJulian M Bucknall ∙ CTO ∙ DevExpress

@jmbucknalljulianb@devexpress.comhttp://devexpress.com/julian

top related