Thursday, 19 January 2012

Javascript Functions:-

A JavaScript function is really an object. As objects, functions can also be assigned to variables, passed as arguments to other functions, returned as the values of other functions, stored as properties of objects or elements of arrays, and so on.

function fun1(x) {

fun1['userId'] = '123';// functions can also be assigned to variables

alert(fun1.userId);//displays 123


var fun2 = function (x) {



var fun3 = new Function("x,y", "alert(y);");

fun3("1", "2");


var arr = [];

arr[0] = function (x) { return x * x; };

alert(arr[0](2)); //displays 4

var obj = { "append": function (x) { return x + 'b'; }, "username": 'abc' };

alert(obj.append('a')); //displays ab

// passing  function as an argument to another function
function square(x) {
return x * x;

function calc(num, func) {
return func(num);

alert(calc(2, square)); //displays 4

//functions as return values
function add() {
return function (x, y) {
return x + y;

var res = add();

alert(res(1, 2)); // displays 3

//Remember, a function in JavaScript is an object. Every function object has a method named //call, which calls the function as a method of the first argument. That is, whichever object we //pass into call as its first argument will become the value of "this" in the function invocation.
function displayname() {

var userObject = { 'userId': '123', 'userName': 'abc' };; // displays 123

//Constructor functions
function userObject(name) { = name;
var user = new userObject("abc"); //var user = {};,, "abc");

Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…

No comments:

Post a Comment