Motivation
Some JS features are hidden under the hood or veiled under some expressions, etc.
This article is about to enlighten some features or approaches that are not on the surface.
Prerequisites
JS knowledge and that’s all.
Case #1
We have a simple code:
return {
sum: a + b,
multiplied: a * b
}
}
This function just returns an object with sum and multiplied values.
We can invoke the function like:
But also we can modify our function to:
this.sum = a + b
this.multiplied = a * b
}
In this case, we have no return statement, but in the return of invocation like this:
we will have the same structure, smth like this:
sum: 3,
multiplied: 2,
__proto__: { constructor: ƒ test() }
}
Case #2
The typical way to invoke the function:
testFunction(a,b,c)
but we have another method to invoke if we have no args(e.g):
return { message: “Hi there!“ }
}
const data = new test
console.log(data.message) // -> “Hi there!”
Case #3
The regular way that we can use it provides the object on the return statement inside the function, but we can use it outside if we need it.
Regular:
return { message: “Hi there!“ }
}
console.log(test()) // -> “Hi there!”
Weird, but possible:
return { message: “Hi there!“ }
}
test.useTest = function(){
return this()
}
console.log(test.useTest()) // -> “Hi there!”
for example in React we can use this approach for compositing our components.
Conclusion
JS is tricky and not as simple as it looks.