Reading some legacy code, and found
A.prototype.setSize: function () {
var v1 = new Vector2();
return function (size ) {
var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
this.min.sub( halfSize );
return this;
};
}(),
I am wondering:
any light to shed on this?
Updated:
I can simply use
A.prototype.setSize: function (size) {
var v1 = new Vector2();
var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
this.min.sub( halfSize );
return this;
},
Is the first snippet better than second?
v1
each time it is called without making v1
a global (or otherwise non-private)setSize
It function closure. Used to hide variables from global scope. Read on and see some examples here
JS function closures
The purpose in that particular case is to avoid creating a new Vector
object each time setSize
is called. It's a caching strategy. The alternative would be to just have a flat function:
A.prototype.setSize: function (size) {
var v1 = new Vector2();
var halfSize = v1.copy(size).multiplyScalar(0.5);
this.min.sub(halfSize);
return this;
}
I would only use the closure cached version of setSize
if I found I was having performance problems because of new Vector2()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With