HTML and CSS Reference
In-Depth Information
8.1.2 Creating an Object with a Constructor
JavaScript allows you to create an object in a number of ways. One way is with a con-
structor. A constructor is a special kind of function that creates the blueprint for an
object. The new keyword precedes the name of the constructor that will be used to create
the object. By convention, constructor names start with a capital letter to distinguish
them from ordinary functions.
var myNewObject = new Object(argument, argument, ...)
To create the cat object, for example, you could say:
var cat = new Object();
The new Operator. The new operator is used to create an instance of an object. To
create an object, the new operator is followed by the name of a function. The new oper-
ator treats the function as a constructor. This function may be a JavaScript constructor
or one that is user-defined. JavaScript comes with several built-in constructors, such as
Object() , Array() , Date() , and RegExp() . With them you use the new operator followed
by the constructor function and any arguments it takes. A reference to the object is
returned and assigned to a variable.
var car = new Object();
var friends = new Array("Tom", "Dick", "Harry");
var holiday = new Date("July 4, 2011");
var rexp = new RegExp("^[a-zA-Z]");
The Object() Constructor. JavaScript provides a special predefined constructor
function called Object(), used with the new keyword, to build a generic object. The
return value of the Object() constructor is assigned to a variable. The variable contains
a reference to an instance of a new object. See Example 8.1. Later we will create a user-
defined function that will act as a constructor.
FORMAT
var myobj = new Object();
EXAMPLE 8.1
<html>
<head><title>The Object() Constructor</title>
<script type = "text/javascript">
1
var cat = new Object();
2
alert(cat);
</script>
</head>
<body></body>
</html>
 
 
Search WWH ::




Custom Search