Defining A Function Inside A Template Literal
Solution 1:
Yes, it would define a new version of the function each time the template literal is interpolated. You can verify that by defining your own tag that keeps track of the previous value.
var previous;
functiontrackInterpolations(literalParts, interpolated) {
if (interpolated === previous) {
answer = 'Got the same function';
} else {
answer = 'Got a different function';
}
previous = interpolated;
return answer;
}
Then run
trackInterpolations`background: ${props => props.isMatching ? 'green' : 'red'};`
a couple of times and notice that it always evaluates to 'Got a different function'
, indicating that it's creating a new function each time.
Compare that to this version:
trackInterpolations`background: ${isMatchingFn};`
The first time it's run, it will evaluate to 'Got a different function'
(because it hasn't seen the isMatchingFn
yet), but if you evaluate it a few more times it will always result in 'Got the same function'
, because the function reference is being reused.
I wouldn't worry too much about the performance impact though in this case, and go with whatever is more readable unless you actually notice a slowdown. Compared to re-rendering the div, the overhead of creating a new function isn't likely to be very high.
Post a Comment for "Defining A Function Inside A Template Literal"