在 Javascript 中使用 this.variable 作为参数默认值有什么问题吗?

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

如果我有一个 ES6 class 比如:

class Foo {
  constructor(bar) {
    this.bar = bar;
  }
  echo(value=this.bar) {
    return value;
  }
}

this.bar 应在每次调用 echo 时重新计算。

f = new Foo(10);
f.echo();
>> 10
f.bar = 99;
f.echo();
>> 99

这种用法是否会产生任何潜在问题?

嗯..

echo(value=this.bar)value 设置为 this.bar 如果 value === undefined 正如评论中指出的那样。所以你在做:value = value === undefined ? this.bar : value;

这与做的事情基本相同:

class Foo {
  constructor(bar) {
    this.bar = bar;
  }
  echo(value) {
    let value = value === undefined ? this.bar : value;
    return value;
  }
}

如果这就是您想要的 - 完全没问题。

这在技术上是正确的,但最好尽可能缩小范围。过度使用全局 (this) 变量会导致混乱或 hard-to-read 代码又名 spaghetti code.

除了常见的 js this 问题外,没有什么大问题需要担心。 您可以使用调用、绑定等方法将值注入此方法。 这也可能导致错误和不一致。

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);
}

在方法中使用时出现default param is evaluated at call time, so as long as this hasn't been bound by .bind(), .call(), or .apply(), it will always refer to the object it's called on

我没有发现任何问题,除非您要扩展 Foo,并在一个也有 bar 属性[= 的子对象上调用 echo 14=]