As far as I understand, in JavaScript (Gecko variant) this:
var a = new A();
is a syntactic sugar for something like this:
var a = {};
a.__proto__ = A.prototype;
A.call(a);
Because of that, A() (which is equivalent to A.call()?) and new A() should produce two different results, like these:
>>> new Date()
Fri Nov 19 2010 01:44:22 GMT+0100 (CET) {}
>>> typeof new Date()
"object"
>>> Date()
"Fri Nov 19 2010 01:44:42 GMT+0100 (CET)"
>>> typeof Date()
"string"
So far so good.
But, core object Function behaves differently:
>>> Function('return 123;')
anonymous()
>>> typeof Function('return 123;')
"function"
>>> Function('return 123;')()
123
>>> new Function('return 123;')
anonymous()
>>> typeof new Function('return 123;')
"function"
>>> new Function('return 123;')()
123
Am I missing some trivial thing here ?
JavaScript at a language level doesn’t specify a particular ‘standard’ way of using constructors. When you define your own constructor function, you can choose to have it callable as a constructor (with
new), as a function (returning a new object), or make it work with either.Not really. The
Functionconstructor function is defined to be usable as a constructor even withoutnew, by ECMAScript section 15.3.1:The
Datefunction, on the other hand, is defined (by ECMAScript section 15.9.2) to return a string:The NOTE is there because so many constructor functions can also be used without
new. That’s not because of any over-arching thinking that all constructor functions should be allowed to work as plain functions, but because this is just what JavaScript has always done since the early Netscape days. Netscape couldn’t think of anything special forFunction()to do, so it just reproduced thenewfunctionality. They didn’t pay too much attention to making the language consistent.You wouldn’t design a language’s default class library like that if you were sane. But JavaScript isn’t a sane language. It’s a quick hack that got way out of hand, achieving mass popularity way before anyone spent any time refining its design. Expect it to behave consistently and you will only be disappointed.