Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any issues with using a this.variable as an argument default in Javascript?

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?

like image 482
rovyko Avatar asked May 15 '19 20:05

rovyko


1 Answers

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);
}
like image 117
Bellian Avatar answered Sep 18 '22 10:09

Bellian