By creating a new instance of someClass() and chaining a function to the same variable, will a new someClass be created every time I call someFunc()?
const someFunc = new someClass().getOrSetOrWhatever()
compared to if I write it as is usually done
let s = new someClass()
s.getOrSetOrWhatever()
And if I put the first example into a constructor, would it mean that there would be only one instance (everytime I called this.someFunc)? Would it be bad practice? Thanks in advance!
Every time you call new someClass()
a new instance of someClass is created. The "new" keyword causes a unique "copy" of the class to generate an new, unique copy (instance).
When you execute getOrSetOrWhatever()
chained to new someClass()
as:
let s = new someClass().getOrSetOrWhatever()
Then the "s" variable will contain the result of getOrSetOrWhatever (whatever that function returns).
HOWEVER, the instance that new someClass()
generated will exist, but not be accessible because it was never assigned to a variable (potential memory leak) -- only the result of getOrSetOrWhatever is returned.
Chaining passes whatever is generated/returned on the left to the right.
foo().bar()
// is like:
// foo() --> bar()
// or
// the method "bar" is within "foo"
When you don't chain as in:
let s = new someClass();
let foo = s.getOrSetOrWhatever();
Then the instance is assigned to the s
variable and foo
is assigned to whatever "getOrSetOrWhatever" returns.