Newbie question about "NEW: Keyword

M

mscurto

Hello,

I am new to Javascripting but I am having a hard time with one of the
basics. When do you use the NEW Keyword and when do you not need it?

For some reason, I have had a very hard time getting this concept down.
Can anyone explain this in real simple terms for me?

I've searched the Internet for a simple explanantion and I cannot find
one.

Help!
 
V

VK

Hello,

I am new to Javascripting but I am having a hard time with one of the
basics. When do you use the NEW Keyword and when do you not need it?

For some reason, I have had a very hard time getting this concept down.
Can anyone explain this in real simple terms for me?

I've searched the Internet for a simple explanantion and I cannot find
one.

Because there is not really plain two-words explanations. "new" is not
an operator like * (say "multiplication sign" and you are done) - it is
a part of concept. The maximum plain explanation would be something
like: "new operator create new instance of object using indicated
function-constructor".

Say
var date1 = new Date();
can be read as "create new instance of Date object with all predefined
properties and methods and name this instance date1".

You can create your own function-constructors and create instances from
these constructors.

You should really read some plain vanulla samples with maximum human
language explanations :) MSDN is not so bad for that:

<http://msdn.microsoft.com/library/en-us/script56/html/5ea556ba-7ae6-426c-8430-9032eee5a0a5.asp>
<http://msdn.microsoft.com/library/en-us/script56/html/e869702e-4caf-4513-8dd5-fe690535f8aa.asp>
 
M

MS

My understanding is that you use the NEW keyword when creating
instances of objects, since you cannot change the properties of the
Date object directly, for example. If you want to change the value of
the Date object, you need to create an instance of it, through a
variable and NEW keyword.

I guess part of my problem is what are the objects you need to use the
NEW keyword for? I know DATE() is one of them but is there a list
somewhere that can be used as a reference?

Am I accurate in what I wrote here?
 
V

VK

MS said:
My understanding is that you use the NEW keyword when creating
instances of objects, since you cannot change the properties of the
Date object directly, for example. If you want to change the value of
the Date object, you need to create an instance of it, through a
variable and NEW keyword.

I guess part of my problem is what are the objects you need to use the
NEW keyword for? I know DATE() is one of them but is there a list
somewhere that can be used as a reference?

Am I accurate in what I wrote here?

Oohm... kind of... :)

If we are talking about JavaScript native objects, then the only object
you have to use with new is Date - if you need to get current time.
"use with new keyword"... that's something... OK, let it go for
now...:).

Nowhere else you are *required* to use new keyword. Typically one also
"uses new keyword" to create new Array and new Object, but bracket
notation can do it as well:
var arr = new Array(1.2.3) // equals to var arr = [1,2,3];
var obj = new Object() // equals to var obj = {};

There is a very particular case where you need to use String()
constructor:- to exclude new instance from the common prototype chain.
You may guess by the description that this case is currently our of you
interest (no offence ;-)

So the required list for native objects is plain and short: Date()
 
M

MS

I was going to say I see various objects in my Javascript textbook.
Date, Document, Form, History, Image, Location, Math, etc..

So I wouldn't need to use NEW when creating instances of these to
change values, etc.?

I do appreciate the feedback - thanks.
 
L

Lasse Reichstein Nielsen

MS said:
My understanding is that you use the NEW keyword when creating
instances of objects,

To be terminologically exact (which is a good idea when trying to
understand something - it's safer to get lazy when you understand
what you are talking about :), you create *objects*. In other, class
based, languages, objects are instances of classes. Javascript
does not have classes, so "instance" is a word to avoid. It only
confuzes. "Instance of object" is overdoing it :)
since you cannot change the properties of the
Date object directly, for example.

The "Date" object (i.e., the function object accessible through
the global property "Date") is used as a constructor function.
It doesn't have any value to change.

You can think of constructor functions as somewhat similar
to classes, but the similarity is only skin deep. They are
closer to initializer/constructor-methods of a class than to
classes themselves. In Javascript they initialize new objects
with values, but the objects themselves have no type/class.

The "date object" that you create using "new Date()" is completely
different. It is not a function, but an object that represents
a point in time.

You use the "new" operator with a constructor function to
create a new object. The constructor function initializes
the new object, and the object accessible through the
"prototype" property of the constructor function object
(functions are objects) is used as the inheritance chain
of the new object - i.e., the properties of this "prototype
object" can be read as properties of the new object unless
shadowed by properties directly assigned to the new object.
If you want to change the value of the Date object, you need to
create an instance of it, through a variable and NEW keyword.

The Date constructor function doesn't have a value at all, so
there is nothing to change. The date objects you create from
it do have a time value, and it can be changed.
I guess part of my problem is what are the objects you need to use the
NEW keyword for? I know DATE() is one of them but is there a list
somewhere that can be used as a reference?

You can use "new" with any function, using it as a constructor
function. Some functions have been created with that use in mind. In
the ECMAScript language, this includes the functions available through
the global variables named:
Object
Array
String
Number
Boolean
Function
RegExp
Date
Error

For Object, Array, Function and RegExp, the language have notation
for creating new objects besides using "new" (being: {}, [...],
function(...){...}, and /.../).
You only need to use "new" with these types for backwards compatability
with old versions of Javascript before the literal syntax was introduced.

I have yet to need to create an object from String, Number and
Boolean. These objects are different from the simple type values
they wrap, i.e., "new Number(4)" is an object where "4" is a number.
Javascript automatically creates a new wrapper object when using
property accessor notation, so
"abc".substring(1,1)
is equivalent to
new String("abc").substring(1,1)
The only case where I can see creating a new object explicitly to
be useful is if such a property access is inside a tight loop
and always on the same string (or other value). The creating the
object outside the loop avoids creating a new object implicitly
for each iteration.

This leaves only Date and Error, and I haven't used Error for anything
yet :). Also, "Error()' is equivalent to "new Error()", so "new" is
not needed (the same applies to RegExp and Function, which also create
new objects when called as a function).
Am I accurate in what I wrote here?

Close, but it can always be more accurate (just get a pedant like me
started :)


I use "instance" myself when talking about objects created from a
constructor function, i.e., "an instance of Date" instead of
"an object created by 'new Date()'", but that *is* being lazy.

/L
 
L

Lasse Reichstein Nielsen

MS said:
I was going to say I see various objects in my Javascript textbook.
Date, Document, Form, History, Image, Location, Math, etc..

Math is just an object, not a constructor function, so you can't
use "new" with it.

Document, Form and Image are DOM element types. The first twoq should
be created using document.createDocument() and document.createElement("form").
There is tradition for using "new Image()" to create a new image object,
but document.createElement("img") should work as well.

The history object (a property of the window object) is just an object.
You can't create new histories yourself (that would be revisionist :)
Location likewise.

/L
 
T

Thomas 'PointedEars' Lahn

Lasse said:
Math is just an object, not a constructor function, so you can't
use "new" with it.

Document, Form and Image are DOM element types.

Those are and create "DOM Level 0" objects. The identity with (W3C) DOM
element objects is merely a peculiarity of DOM implementations that try
to be backwards compliant. See below.
The first twoq should be created using document.createDocument() and
document.createElement("form").

Those calls should create HTMLDocument objects and HTMLFormElement objects,
respectively, which implement the corresponding interfaces of W3C DOM Level
1+ HTML.
There is tradition for using "new Image()" to create a new image object,
but document.createElement("img") should work as well.

Those are, by definition, different objects. The former should create
an Image object, the latter should create an HTMLImageElement object.
The Gecko DOM does not appear to make any difference there anymore, though.
The history object (a property of the window object) is just an object.
You can't create new histories yourself (that would be revisionist :)
Location likewise.

Those are and create also (proprietary) "DOM Level 0" objects.

With the transition from Client-side JavaScript 1.3 to Core JavaScript 1.5
(with the intermittent step of JavaScript 1.4 implemented only server-side
in the iPlanet Web Server and its successors, the core language already
without DOM/AOM-related objects), objects and properties specific to the
Netscape Navigator AOM/DOM were removed from the core JavaScript language,
and added to the Netscape Gecko DOM, which became the current Gecko DOM as
developed by the Mozilla Organization and contributors from the global
community.

However, Microsoft JScript (for IE) and other ECMAScript implementations
copied objects that were still defined as core objects in JavaScript < 1.4,
which is why the so-called "DOM Level 0" (starting with NN3/IE3) exists.
The W3C DOM Level 1+ HTML interfaces officially specify many of these
previously only proprietary features (such as HTMLDocument::forms, images,
URL etc). They do not specify features that are not document-related,
though, such as History and Location; that is left to the (necessarily)
proprietary Application Object Model specifications of vendors.


PointedEars
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
Yes, it has. You are confusing "value" with "return value".

Not at all. Mr. "MS" was talking about the value you can change
in a date object (created by the Date constructor function), i.e.,
the actual time value. The Date constructor function doesn't have
such a value that is immutable, and in fact it doesn't have it at
all.

I am not sure what value you think the Date constructor function
has (itself being a value that it *is*, not one that it *has*).

/L
 
T

Thomas 'PointedEars' Lahn

Lasse said:
Not at all. Mr. "MS" was talking about the value you can change
in a date object (created by the Date constructor function), i.e.,
the actual time value. The Date constructor function doesn't have
such a value that is immutable, and in fact it doesn't have it at
all.

I am not sure what value you think the Date constructor function
has (itself being a value that it *is*, not one that it *has*).

I don't see your point. Everything that is a value also has a value
in an expression.


PointedEars
 
M

MS

My original question - so anytime I want to create a new object I use
the NEW keyword?

I can create any object with any name, right? Why would I want to do
this as part of Javascripting?
 
J

jshanman

MS said:
My original question - so anytime I want to create a new object I use
the NEW keyword?

Yes, anytime you want a NEW object (custom,Date,Error,Image,Array,
etc), use the NEW keyword.
I can create any object with any name, right? Why would I want to do
this as part of Javascripting?

Say your creating a page with lots of addresses. You can create a
contructor function for your records...

function CreateRecord(fname,lname,add1,add2,city,state,zip,country) {
this.fname = fname;
this.lname = lname;
this.add1 = add1;
this.add2 = add2;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
this.GetFullName = function() {return fname+" "+lname;}
}

//You then access this custom object contructor like this.

var AllRecordsObj = new Object();
AllRecordsObj["Record1"] = new CreateRecord("john","smith","12345
Main","Apt 10","NY","NY","55555","USA");
AllRecordsObj["Record2"] = new CreateRecord("jill","smithy","54321
Main","Apt 9","NY","NY","55555","USA");

//now loop through write all the first names...
for (prop in AllRecordsObj) {
var fullName = AllRecords[prop].GetFullName();
document.writeln(prop+": "+fullName+"<br />");
}

This would output:

Record1: john smith
Record2: jill smithy

- JS
http://www.endeavorpub.com
 
T

Thomas 'PointedEars' Lahn

jshanman said:
Yes, anytime you want a NEW object (custom,Date,Error,Image,Array,
etc), use the NEW keyword.

Wrong if this absolute, as was already explained. Would you please care
to read before you post?
I can create any object with any name, right? Why would I want to do
this as part of Javascripting?

Say your creating a page with lots of addresses. You can create a
contructor function for your records...

function CreateRecord(fname,lname,add1,add2,city,state,zip,country) {
this.fname = fname;
this.lname = lname;
this.add1 = add1;
this.add2 = add2;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
this.GetFullName = function() {return fname+" "+lname;}
}

//You then access this custom object contructor like this.

var AllRecordsObj = new Object();
AllRecordsObj["Record1"] = new CreateRecord("john","smith","12345
Main","Apt 10","NY","NY","55555","USA");
AllRecordsObj["Record2"] = new CreateRecord("jill","smithy","54321
Main","Apt 9","NY","NY","55555","USA");

However, the better approach here is to pass an object to the constructor
so you do not have to provide all the data for each record (not even empty
one).

The constructor identifier, which is the only identifier here that should
start with a capital letter (just code style), should identify the object,
not the action; it is obvious that something (an object) is created by it.

And the method GetFullName() should be a prototype method, so that its code
can be reused by objects, and there is only one Function object created for
it (runtime and memory efficiency). It MUST either be a prototype method,
or a reference to the calling object's properties must be used in it
instead of a reference to the arguments; otherwise the closure will not
allow it to return any other but the initial data.

function Record(data)
{
// the empty string is the default value for all properties, see below
this.fname = data.fname || "";
this.lname = data.lname || "";
this.add1 = data.add1 || "";
this.add2 = data.add2 || "";
this.city = data.city || "";
this.state = data.state || "";
this.zip = data.zip || "";

// if no value is specified or it is a false-value (such
// as the empty string), the default/ ("USA") is assigned
this.country = data.country || "USA";
}

Record.prototype.getFullName = function()
{
return this.fname + " " + this.lname;
};

Instead of
var AllRecordsObj = new Object();
AllRecordsObj["Record1"] = ...
[...]

one can safely use

var records = {
// this person lives in the USA despite it is not explicitly specified
Record1: new Record({
fname: "john",
lname: "smith",
add1: "12345 Main",
add2: "Apt 10",
city: "NY",
state: "NY",
zip: "55555"
}),

Record2: new Record({
// ...
})
};

nowadays (JavaScript 1.3+ [NN 4.06+, 1998+], JScript 3.0+
[IE 4.0+, Oct. 1997+], ECMAScript Ed. 3+ [Dec. 1999+]).

However, an Array object probably is more appropriate here,
to have each record "numbered automatically":

var records = [
new Record({
fname: "john",
lname: "smith",
add1: "12345 Main",
add2: "Apt 10",
city: "NY",
state: "NY",
zip: "55555"
}),

new Record({
// ...
})
];
//now loop through write all the first names...
for (prop in AllRecordsObj) {

This will iterate through all enumerable properties,
which is sometimes not desired. Search the archives.

The array data structure, encapsulated by the Array
object created through the above literal notation,
can be iterated as follows:

for (var i = 0, len = records.length; i < len; i++)
{
// ... records ...
}


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top