If I have an ES6 class like:
class Foo {
constructor(bar) {
this.bar = bar;
}
echo(value=this.bar) {
return value;
}
}
this.bar
should be re-evaluated each time echo
is called.
f = new Foo(10);
f.echo();
>> 10
f.bar = 99;
f.echo();
>> 99
Are there any potential issues that could come from this usage?
Well there is nothing BIG to be concerned of, except the usual js this
problem.
You can inject values into this method using the call, bind, etc method.
This could also cause errors and inconsistencies.
class Foo {
constructor(bar) {
this.bar = bar;
}
echo(value=this.bar) {
return value;
}
}
f = new Foo(10);
console.log('f', f.echo().toFixed(0))
console.log('f', f.echo.call({bar: 50}).toFixed(0))
try{
console.log('f', f.echo.call(window).toFixed(0))
}catch(e){
console.error(e);
}
class Fooo {
constructor(bar) {
this.bar = bar;
// fixing the scope
this.echo = (value=this.bar) => {
return value;
}
}
}
f2 = new Fooo(10);
console.log('f2', f2.echo().toFixed(0))
console.log('f2', f2.echo.call({bar: 50}).toFixed(0))
try{
console.log('f2', f2.echo.call(window).toFixed(0))
}catch(e){
console.error(e);
}
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