Javascript: Supercharge Your HTML
Javascript: Supercharge Your HTML
Objectives
Understand the concept of functions Be able to define functions Identify the different ways of invoking a functions Identify and apply the different properties and methods of functions
JavaScript Functions
A function is a block of JavaScript code that is defined once but may be executed, or invoked, any number of times.
function add(num1, num2){ return num1 + num2; } add(5,9); //Returns 14 add(2,2); //Returns 4 add(9,-2); //Returns 7
JavaScript Functions
JavaScript functions are parameterized: a function definition may include a list of identifiers, known as parameters, that work as local variables for the body of the function.
function add(num1, num2){ return num1 + num2; } /* Identifiers num1 and num2 inside the parentheses are the parameters of this function */
JavaScript Functions
Function invocations provide values, or arguments, for the functions parameters.
function add(num1, num2){ return num1 + num2; } add(5,9); // The values 5 and 9 are the arguments passed to the function
JavaScript Functions
Functions often use their argument values to compute a return value that becomes the value of the function-invocation expression.
function add(num1, num2){ return num1 + num2; // We return the total of the arguments } add(5,9); // The values 5 and 9 are the arguments passed to the function
JavaScript Functions
In addition to the arguments, each invocation has another valuethe invocation contextthat is the value of the this keyword.
var word = bird;
Defining a function
Functions are defined with the function keyword, which can be used in a function definition expression or in a function declaration statement. In either form, function definitions begin with the keyword function followed by these components: an identifier that names the function a pair of parentheses around a comma-separated list of zero or more identifiers
Invoking functions
The JavaScript code that makes up the body of a function is not executed when the function is defined but when it is invoked. JavaScript functions can be invoked in four ways: as functions as methods as constructors
Invoking as function
An invocation expression consists of a function expression that evaluates to a function object followed by an open parenthesis, a comma-separated list of zero or more argument expressions, and a close parenthesis.
For regular function invocation, the return value of the function becomes the value of the invocation expression.
Invoking as method
A method is nothing more than a JavaScript function that is stored in a property of an object.
var person = { firstname : Juan, middlename : Samonte, lastname : dela Cruz, fullname : function(){ return this.firstname+ +this.middlename+ +this.lastname } }
alert(person.fullname());
this keyword
Note that this is a keyword, not a variable or property name. JavaScript syntax does not allow you to assign a value to this.
Unlike variables, the this keyword does not have a scope, and nested functions do not inherit the this value of their caller.
If a nested function is invoked as a function then its this value will be either the global object (non-strict mode) or undefined (strict mode).
var o = { m: function() { var self = this; // Save the this value in a variable. alert(this === o); // Displays "true": this is the object o.
f(); // Now call the helper function f(). function f() { // A nested function f alert(this === o); // "false": this is global or undefined alert(self === o); // "true": self is the outer this value. } } }; o.m();
Invoking as constructor
If a function or method invocation is preceded by the keyword new, then it is a constructor invocation.
var o = new Object(); var o = new Object; Var list = new Array(5);
Indirect invocation
JavaScript functions are objects and like all JavaScript objects, they have methods. Two of these methods, call() and apply(), invoke the function indirectly.
Both methods allow you to explicitly specify the this value for the invocation, which means you can invoke any function as a method of any object, even if it is not actually a method of that object.
The first invocation of f() will display the value of 10, because this references the global object.
The second invocation (via the call method) however, will display the value 15. 15 is the value of the x property inside object o.
Optional parameters
When a function is invoked with fewer arguments than declared parameters, the additional parameters are set to the undefined value.
function join(array, delimiter){ var tmp_string = ""; for(var i = 0; i < array.length; i++){ tmp_string += array[i]; if(i != array.length - 1){ if(delimiter === undefined){ tmp_string += ","; } else { tmp_string += delimiter; } } } }
Functions like this one that can accept any number of arguments are called variadic functions, variable arity functions, or varargs functions. function average(/*...*/){ var total = 0; for(var i = 0; i < arguments.length; i++){ total += arguments[i]; } return total / arguments.length;
Argument types
JavaScript method parameters have no declared types, and no type checking is performed on the values you pass to a function. In our previous example, the function accepts multiple number of arguments and find their average. The function should be able to check that the data type of all the arguments is a number.
function average(/*...*/){ var total = 0; var number_of_arguments = 0; for(var i = 0; i < arguments.length; i++){ if(typeof arguments[i] == number){ total += arguments[i]; total_numbers++; } } return total / number_of_arguments; }
Function as Values
Function definition and invocation are syntactic features of JavaScript and of most other programming languages. In JavaScript, however, functions are not only syntax but also values, which means they can be assigned to variables, stored in the properties of objects or the elements of arrays, passed as arguments to functions, and so on.
The name of a function is really immaterial; it is simply the name of a variable that refers to the function object. The function can be assigned to another variable and still work the same way:
var s = square; //Now s refers to the same function that square does square(4); // Returns 16 s(4); // Returns 16
Functions can also be assigned to object properties rather than variables. When you do this, theyre called methods:
var o = {square: function(x) { return x*x; }}; // An object literal var y = o.square(16); // y equals 256
// This function returns a different integer each time it is called. function uniqueInteger() { return uniqueInteger.counter++; // Increment and return counter }
length property
This read-only property returns the arity of the functionthe number of parameters it declares in its parameter list, which is usually the number of arguments that the function expects.
function check(args) { var actual = args.length; // The actual number of arguments var expected = args.callee.length; // The expected number of arguments if (actual !== expected) // Throw an exception if they differ. throw Error("Expected " + expected + "args; got " + actual); } function f(x, y, z) { check(arguments); // Check that the actual # of args matches expected #. return x + y + z; // Now do the rest of the function normally. }
prototype property
Every function has a prototype property that refers to an object known as the prototype object. Every function has a different prototype object. When a function is used as a constructor, the newly created object inherits properties from the prototype object.
bind() method
As its name implies, the primary purpose of bind() is to bind a function to an object.
Example: When you invoke the bind() method on a function f and pass an object o, the method returns a new function. Invoking the new function (as a function) invokes the original function f as a method of o. Any arguments you pass to the new function are passed to the original function.
function f(y) { return this.x + y; } // This function needs to be bound var o = { x : 1 }; // An object we'll bind to var g = f.bind(o); // Calling g(x) invokes o.f(x) g(2) // => 3
Function() constructor
Functions are usually defined using the function keyword, either in the form of a function definition statement or a function literal expression. But functions can also be defined with the Function() constructor.
var f = new Function("x", "y", "return x*y;"); //Is equivalent to var f = function(x, y) { return x*y; }
The Function() constructor expects any number of string arguments. The last argument is the text of the function body. All other arguments to the constructor are strings that specify the parameters names for the function. You simply pass a single string if you dont need to define paramaters.
SUMMARY:
A function is a block of code that can be invoked several times.
Function parameters are values that are expected when you invoke the function. Arguments are values passed to the function when invoked. Functions has properties and methods that provides flexibility in invoking functions.
JavaScript
supercharge your HTML