Book Image

Object-Oriented JavaScript

By : Stoyan Stefanov, Stoyan STEFANOV
Book Image

Object-Oriented JavaScript

By: Stoyan Stefanov, Stoyan STEFANOV

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

Function


JavaScript functions are objects. They can be defined using the Function constructor, like so:

>>> var sum = new Function('a', 'b', 'return a + b;');  

This is equivalent to the function literal:

>>> var sum = function(a, b){return a + b;};

or the more common:

>>> function sum(a, b){return a + b;}

The use of the Function constructor is discouraged in favor of the function literals.

Members of the Function Objects

Property/Method

Description

apply(this_obj, params_array)

Allows you to call another function while overwriting its this value. The first parameter that apply() accepts is the object to be bound to this inside the function and the second is an array of parameters to be passed to the function being called.

function whatIsIt(){
  return this.toString();
}
>>> var myObj = {};
>>> whatIsIt.apply(myObj);

"[object Object]"

>>> whatIsIt.apply(window);

"[object Window]"

call(this_obj, p1, p2, p3, ...)

Same as apply() but accepts parameters one by one, as opposed to as one array.

length

The number of parameters the function expects.

>>> alert.length

1

>>> parseInt.length

2