Message from JavaScript discussions

June 2017

— > new (function boop() {})
boop {}
> new (function boop() {})()
boop {}

— 

It returns an empty object (which is instanceof the calling function) unless the function modifies this

— Empty object is passed into the function as this

— Oh, I see. I wonder what the criteria is for that error then

— Must be implemented within the function

— Function MyClass() {
if (!(this instanceof MyClass)) {
throw Error('Not a constructor');
}
}

— Stuff like Math will probably throw that to avoid confusion

— Wonderful

— Yup

— > new Math()
TypeError: Math is not a constructor

— Apart from my now-apparent wrong assumptions, you did say this is not a problem. Care to elaborate?

— Well, my approach is always using symbols:

(in own file, aka wrapped in IIFE):

const priv = new Symbol();

class MyClass {
constructor () {
this[priv] = { value: 42 };
}
digitSum () {
return String(this[priv].value)
.split('').reduce((sum, digit) =>
sum + digit, 0);
}
}

Message permanent page