6
Assuming the function:
function foo() {
return 'something';
}
It is possible to invoke it (abstract operation [[Call]]
):
// Invocando `foo`:
foo();
In the above example, the string would be returned something.
But it is also possible to use it as a constructor (abstract operation [[Construct]]
):
// Construindo um novo objeto `foo`:
new foo();
In the above example, how foo
was not created for the purpose of act as constructor, an "empty" object (of the "type" foo
) is returned.
There are cases like this where a function should not be used as a builder, so I wonder if it is possible to prevent the use of new
.
I know that in some cases can be useful (especially when class
did not exist), but would like to know if you can "block" (i.e. throw error) when trying to use new
in foo
? I mean, I just want the invocation to be allowed.
It is possible?
from the point of view of javascript prototyping is even interesting but... in which real case would someone want to need it? I confess I’ve never seen anyone try to use a Function (which exists only as a "method") as an instance, and I’ve seen a lot of code in my life :)
– Ricardo Pontual
I also maintain your inquiry, @Ricardopunctual, in fact is a use case unusual. Anyway, I don’t think it’s appropriate to think "where it could be used" (because it’s impossible to list this kind of possibility), but yes show the possibility.
– Luiz Felipe
I understand, I just wanted to know if there are any use cases for this, but as I said, as knowledge is interesting, but it would be more if I had some practical example :)
– Ricardo Pontual
@Ricardopunctual, there is some use. See the example of this post on Soen. It talks about the difference in using
let d = new Date();
andlet d = Date();
in the first case an object is returnedDate
and in the second case aString
with the current date.– Augusto Vasques