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) {
alert(x);
}

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

alert(fun1.userId);//displays 123


//(or)

var fun2 = function (x) {
alert(x);
};

fun2("fun2");

//(or)

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

fun3("1", "2");

//(or)

var arr = [];

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

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

//(or)
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() {
alert(this.userId);
}

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

displayname.call(userObject); // displays 123

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




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

No comments:

Post a Comment