具有不一致返回点的函数的JavaScript

时间:2014-04-20 04:08:01

标签: javascript phpstorm

我们说我有这个班级:

function Point(x,y){
  var _x=x,_y=y;
  this.x = function(newX){
    if (typeof newX !== 'undefined') {
      //function x() working as a setter
      _x=newX;
    }
    else {
      //function x() working as a getter
      return _x;
    }
  }
}

PHPStorm抱怨函数(x())具有不一致的返回点。我发现在return undefined;之后添加_x=newX;解决了问题,代码看起来像这样。

function Point(x,y){
  var _x=x,_y=y;
  this.x = function(newX){
    if (typeof newX !== 'undefined') {
      //function x() working as a setter
      _x=newX;
      return undefined;
    }
    else {
      //function x() working as a getter
      return _x;
    }
  }
}

问题是:有没有办法让PHPStorm停止抱怨这个?

2 个答案:

答案 0 :(得分:1)

另一种选择是正确地注释方法返回类型,以便PhpStorm知道在某些情况下该函数应该返回undefined

/**
 * @param {number} [newX]
 * @returns {number|undefined}
 */
this.x = function(newX) {
    // ...
}

答案 1 :(得分:0)

您只能禁止此功能的警告,例如:

//noinspection FunctionWithInconsistentReturnsJS
    this.x = function(newX){
...
}