functions - complex first class citizen
DESCRIPTION
From basic to complex stuff about Functions in JavascriptTRANSCRIPT
Functions - complex first class citizen
Vytautas Butkus
Content
● What is a function?● Defining functions● Calling functions● Context
What is a function?..
Mathematical:f(x) -> x * x
Javascript:function (x) { return x * x;}
Square Function
...what else is a function?
● Functions are objects○ function() {} instanceof Object //true○ Can be passed as an argument
- doMagic(function () {})- function magic() {}; addPower(magic);
○ Can have other objects/functions as properties- typeof $ //"function"- $.Event, $.ajax, $.each, etc..
○ Always passed by reference
- function addPower (fn) { fn.fire = true; }- magic.fire //true;
...what else is a function?
● Function is a scope provider○ No scope in if (condition) { ... } else { ... } blocks○ Variables are scoped to function's body block
...what else is a function?
● Function is a scope provider○ No scope in if (condition) { ... } else { ... } blocks○ Variables are scoped to function's body block
Content
● What is a function?● Defining functions● Calling functions● Context
Defining functions
● Function expression○ var expression = function (arg1, arg2) { ... }○ Anonymous callback functions
● Function declaration○ function declaredFunction (arg1, arg2) { ... }○ always hoisted to the top○ named functions
● IIFE (Immediately-Invoked Function Expression)○ (function () { ... })(); //Anonymous function○ Used to create variable scopes (basically memory leaks)○ Used to define modules (must return reference)
Named functions(function firstClosure () { (function secondClosure () { (function thirdClosure () { (function fourthClosure () { console.log(1); debugger })() })() })()})()
(function () { (function () { (function () { (function () { console.log(1); debugger })() })() })()})()
VS
var activity = function workout () { ... }totally legal
Content
● What is a function?● Defining functions● Calling functions● Context
Calling functions
● Function(arg1, arg2,...);● Function.call(context, arg1, arg2,...);● Function.apply(context, [arguments]);
● setTimeout(Function, delay, arg1, arg2,...);● setInterval(Function, delay, arg1, arg2,...);
○ requestAnimationFrame(...);● new Function(arg1, arg2,...);
Calling functions
● Function(arg1, arg2,...);● Function.call(context, arg1, arg2,...);● Function.apply(context, [arguments]);
● setTimeout(Function, delay, arg1, arg2,...);● setInterval(Function, delay, arg1, arg2,...);● new Function(arg1, arg2,...);
Black magic explained:
1. New object { } is created2. Assign object { } internal [[Prototype]] property to the prototype property of Person
- object { }.[[prototype]] = Person.prototype;3. Call Person as normal, passing it the object { } as this:
- Person.call(object { }, 'Jim');
Content
● What is a function?● Defining functions● Calling functions● Context
Context
● Context === this● this === { ... }
Context
● Context === this● this === { ... }
Thank you! Questions?