Download presentation
Presentation is loading. Please wait.
Published byDwayne Knight Modified over 9 years ago
1
Julian on JavaScript: Functions Julian M Bucknall, CTO
2
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
3
Defining a function −Two main ways: −Function literal −var f = function(arguments) { … }; −var f = function optName(arguments) { … }; −Function statement −function f(arguments) { … }
4
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
5
Invocation −When invoked, all functions get two extra variables −this − −arguments −The parameter values of the call as an array-like object
6
Invocation patterns −Method −Function −Constructor −“apply”
7
Method invocation −Defined as a method on an object −Called via that object − this points to the object containing the method −Like C#, really
8
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
9
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)
10
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
11
“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
12
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
13
Scope 2 −A variable declared in a function is visible throughout the function −Even before it’s lexically defined
14
Closures −The “yay!” to scope’s “ow!”
15
Thank You Julian M Bucknall ∙ CTO ∙ DevExpress @jmbucknall julianb@devexpress.com http://devexpress.com/julian
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.