...

View Full Version : When to declare 'new' object?



darthchocolate
05-01-2008, 05:23 AM
Why and when I should use 'new' to declare a new object or variable. The book I'm reading doesn't explain this, it just says how to do it.
When I first declare a variable, it's already new since it's the first mention of that variable, so why bother to write 'new'?

Trinithis
05-01-2008, 05:43 AM
Let's say you have the following code:



function MyConstructor() {
// no code inside
}

var x = MyConstructor();

var y = new MyConstructor();

alert(x); // alerts undefined
alert(y); // alerts [object Object]


In the first case, the case with x, all you are doing is calling a function. Since the function does not explicitly return a value, it returns undefined.

In the second vase, the case with y, you are telling the interpreter to allocate memory for an object and apply the code in MyConstructor to it, where any instance of the keyword this points to this object.

mrhoo
05-01-2008, 06:22 AM
If you are declaring a variable to be a type that is already defined- a string, or a number, say, the constructor is implied but not necessary-

var s='Some text';
var n= 100;

var s=new String('Some text');
var n= new Number(100);

When you create an instance of a custom object, whose constructor
you have defined, you need the new keyword-

var c=new Collection(/^h\d$/)

Trinithis
05-01-2008, 06:29 AM
Actually these two versions do not generate the same code:



Quote: mrhoo

var s='Some text';
var n= 100;

var s=new String('Some text');
var n= new Number(100);


The former version creates primitives. Primitives are passed by value.

Though I think string primitives might behave oddly. I don't really remember how those are dealt with.


The latter version creates objects and assign references to them to s and n, and the references are passed by value (meaning the objects at the end of the references are implicitly passed by reference).


Almost always the primitive versions are better than the object wrapper versions for performance reasons.

darthchocolate
05-01-2008, 07:53 AM
Okay I understand a little... but why do I see other examples in my book like:
var sObject = new String("Sample string");

if you're going to allocate memory to a var so the var is usable later on, then why assign it a value immediately? If you're assigning the value immediately, then why do you need 'new'?

How is that example code different from:
var sObject = "Sample string";

Trinithis
05-01-2008, 08:20 AM
Just follow the following general rule.

When creating variables of any of the following types:
Boolean
Function
Number
String

Don't create it as an object (aka via new).


Don't use:

var abc = new XXX(...);

Just do this:

var abc = ...

Otherwise, new is 99.9% of the time what you want.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum