If a function is called as a constructor, it's running in the
scope of the newly created object,
The scope within a function is not influenced by how it is called.
There is no such thing as "the scope of a newly created object" (unless
the object is a function).
Are you kidding or being *really* nitpicking? In case ifthe latter I'm
re-phrasing: "when called as a constructor, the function has the newly
created object instance at the top of the scope chain".
A new instance is created at the moment of execution "new SomeObject()"
statement. So it the moment SomeObject() function is called, a new
instance of SomeObject object is already created and placed at the top
of the scope chain so you could fill it with "this.somet hing =..." etc.
That should be clear that you are working with an instance of
SomeObject, not with a generic Object object. Thusly "this.somet hing
=..." etc. is an optional step, you can have a constructor as simple
as:
function SomeObject(){}
and then
var obj = new SomeObject();
which gives you an empty object just like new Object() *but* being an
instance of SomeObject (so its constructor is set properly, instanceof
will act properly and so on).
<html>
<head>
<title>Untitl ed Document</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function CustomObject() {
/* say we want this function to be used
* only as constructor, and not as a
* regular function
*/
window.alert(th is instanceof CustomObject);
if (this == self) {
throw new Error('Illegal constructor call');
}
else {
this.property1 = 'property1';
this.toString = CustomObject.to String;
}
}
// override toString to prevent source dump:
CustomObject.to String = function(){retu rn '';}
try {
var foo = new CustomObject();
window.alert(fo o.property1);
// noop:
var bar = CustomObject();
}
catch(e) {
window.alert(e. message);
}
</script>
</head>
<body>
</body>
</html>