Javascript Lesson 2 - Function Fundamentals
by ironicmuffin
HTML
<html>
<head>
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<h1>Javascript Lesson 2 - Function Fundamentals</h1>
<br />
<p>Example 1: <span id="message"></span></p>
<br />
<p>Example 2: <span id="message_2"></span></p>
<br />
<p>Example 3: <span id="message_3"></span></p>
<br />
<p>Example 4: <span id="message_4"></span></p>
<br />
</body>
</html>
CSS
h1 {
font-weight: bold;
font-size: 18px;
margin: 5px;
}
p {
margin: 5px;
}
JavaScript
/* Standard Function
In JavaScript, we can manipulate functions using other JavaScript code, assign functions to variables, store functions inside arrays, nest functions inside other functions, and pass functions as a parameter to other functions.
It returns the result as a new object (created in object notation) with x and y properties.
*/
function add(point1, point2)
{
var result = {
x : point1.x + point2.x,
y : point1.y + point2.y
}
return result;
}
var p1 = { x: 1, y: 1 };
var p2 = { x: 1, y: 1 };
// use our add function
var p3 = add(p1, p2);
message.innerHTML = p3.x + "," + p3.y;
/* Function as Variables
We could take the same function object and assign it to different variables and invoke the function through those variables.
*/
var foo = add
var bar = add
var p1 = { x: 1, y:1 };
var p2 = { x: 1, y:1 };
// invoke add through foo variable
// p3 should be 2,2
var p3 = foo(p1, p2);
// invoke add again through bar variable
// 2,2 + 1,1 = 3,3
p3 = foo(p3, p1);
message_2.innerHTML = p3.x + "," + p3.y;
// Functions as Methods/Properties of an object
var point1 =
{
x: 3,
y: 5,
add: function(otherPoint)
{
this.x = this.x + otherPoint.x;
this.y = this.y + otherPoint.y;
}
};
var point2 =
{
x: 1,
y: 1
};
// add 3,5 to 1,1
point1.add(point2);
// shows 4,6
message_3.innerHTML = point1.x + "," + point1.y;
/* Sharing functions
We can also assign a function object to an object property. As we noted before, this promotes the function to the status of "method".
The first part of the code uses object notation to create an object with x, y, and add properties. The add property is a function object, and inside we've introduced the "this" keyword. Just as every instance method in C# has an implicit "this" parameter (and every instance method in VB has "Me" parameter), every JavaScript method has an implicit "this" parameter that represents the object through...