JScript, JavaScript, and ECMAScript |
No Java here.
|
JavaScript: Constructor Return Value |
Written August 8th, 2008.
|
What happens when a constructor returns a value?
A constructor in JavaScript is any function which handles being called using the
If a constructor function returns nothing,
Finally, remember that instead of using a global variable, you can store references on the function object itself. I recommend it to better compartmentalize the logic under a single entry in the global namespace, and so it's not actually executed until needed.
A constructor in JavaScript is any function which handles being called using the
new
operator. What happens is a blank Object
is instantiated and accessible to said method via a this
reference. Two things a constructor will typically do is assign a prototype
and add instance-based members. However, you constructors can return values to manipulate what object the caller receives using the return value!If a constructor function returns nothing,
null
, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. For example, a return value of 0
(zero) from a constructor function will be ignored.
function Deebee() { return 0; }
var db = new Deebee();
if (!db)
throw Error("JS constructor returned non-object!");
The second piece of magic eluded to above is the ability for a constructor to return a specific, possibly pre-existing object, rather than a reference to a new instance. This would allow you to manage the number of actual instances yourself if needed; possibly for reasons of limited resources or whatnot.
var g_deebee = new Deebee();
function Deebee() { return g_deebee; }
var db1 = new Deebee();
var db2 = new Deebee();
if (db1 != db2)
throw Error("JS constructor returned wrong object!");
Unfortunately there are no inherent destructors in JavaScript, no way to be called when an object is out of scope and about to be garbage collected. Typically the way to get around this is to write more procedurally when working with scripts controling finite resources, e.g. explicitely call some close/destroy/quit/end/etc. function after you're finished. This is another reason you might opt to share object references so your script can keep track and not exceed any limits which would cause exceptions.Finally, remember that instead of using a global variable, you can store references on the function object itself. I recommend it to better compartmentalize the logic under a single entry in the global namespace, and so it's not actually executed until needed.
function Deebee()
{
if (undefined == Deebee.o)
Deebee.o = this;
return Deebee.o;
}
Check out the full-script example: [ex-constructor-return.js]. You can run this in Windows from a command prompt by typing:
cscript.exe ex-constructor-return.js
Or try it in your web browser by putting it in a HTML document:
<pre> <script language="JavaScript" src="ex-constructor-return.js" > </pre>
Constructor magic! Please post additional tips/tricks or questions as comments.
Difference between 'null' and 'undefined' |
Written May 25th, 2006.
|
Here is one of the most confusing aspects of an otherwise very simple language: two, seemingly redundant ways to represent "no value here buddy, walk it off" (or a fact simile). One is null and the other is undefined. Here's what ECMA3 has to say about these:
It's been a while since I read through the entire thing, but I don't recall it ever getting more specific than that, pretty vague if you ask me. So what is the difference between null and undefined in JavaScript? This is rather difficult to explain for me, so bear with, and these differences seem so subtle as to be almost inconsequential.
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
Running the above script will result in the following output:
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitly set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
You will also get undefined returned when reading a subscript or member that never existed.
Maybe you are seeing the theme in the differences?
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.
The undefined value is a primitive value used
when a variable has not been assigned a value.
The null value is a primitive value that
represents the null, empty, or non-existent reference.
It's been a while since I read through the entire thing, but I don't recall it ever getting more specific than that, pretty vague if you ask me. So what is the difference between null and undefined in JavaScript? This is rather difficult to explain for me, so bear with, and these differences seem so subtle as to be almost inconsequential.
When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:
var s;
WScript.Echo(s);
WScript.Echo("" + s);
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.
You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:
var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));
Running the above script will result in the following output:
undefined
object
Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).
You can explicitly set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.
Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.
var a = [ 'a', 'b', 'c' ];The result of the above script is:
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);
0.) a
1.) undefined
2.) c
You will also get undefined returned when reading a subscript or member that never existed.
Maybe you are seeing the theme in the differences?
The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.