Apologies – I have no idea to how to describe this. Example:
function OutputNumber(number) {
this.outputThisInstead = function (otherNumber) {
console.log(otherNumber);
}
console.log(number);
}
Desired usage:
new OutputNumber(1);
Console output: 1
new OutputNumber(1).outputThisInstead(2);
Console output: 2
Naturally, 1 will always be written to the console, irrespective of what else is called on the object.
I’m after this particular syntax, as well as the behaviour – attaching a function onto the initialisation. It feels impossible since the object must be constructed before any function is called on it, but is this achievable any other way?
It would be possible with a time delay (e.g., in a browser environment,
setTimeoutor similar) and a flag. Not desirable, but possible.Without that, no, you can’t base the action of the constructor on something that hasn’t happened yet. You’d have to instead pass something into the constructor to let it know what was going on.
Browser example (again, I don’t recommend this):
From your comment on the question:
Rather than have the behavior of an earlier function in the chain depend on a later function in the chain, I’d probably add an
.end()at the end of something:endwould output whatever message/messages was/were stored by the previous functions. No need for black magic. Obviously this suffers from the fact that people could fail to put the.end()on, but you need some kind of trigger that it’s okay to do the output, if you want the output to change based on an optional subsequent function call.