Search code examples
javascriptjavascript-objects

"SyntaxError: Unexpected identifier" in javascript class


I have two function in my javascript class where one function is called in another function, I have use the parameter how I use in other programming language. But it is throwing me

"SyntaxError: Unexpected identifier"

class IpSubnetMatch {


 function ip2longConvert(ip)
  {
  var components;
  if(components = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
  {
    var iplong = 0;
    var power = 1;
    for(var i=4; i>=1;i--)
      {
        iplong += power * parseInt(components[i]);
        power *= 256;
      }
    return iplong;
  }
  else return -1;
}

function inSubNet(ip,subnet)
{
  var mask, base_ip;
  var long_ip = ip2longConvert(ip);
  if((mask = subnet.match(/^(.*?)\/(\d{1,2})$/)) && ((base_ip = ip2longConvert(mask[1])) >= 0))
    {
      var freedom = Math.pow(2,32 - parseInt(mask[2]));
      return(long_ip > base_ip) && (long_ip < base_ip + freedom -1);
    }
  else return false;
}
}

let user = new IpSubnetMatch();
user.inSubNet('10.1.5.5', '10.1.0.0/16');

Solution

  • You need to define methods in the class. You also may want to define them as static since they really don't depend on any instance state.

    class IpSubnetMatch {
        ip2longConvert(ip) {
            // ...
        }
        inSubNet(ip,subnet) {
            const long_ip = this.ip2longConvert(ip);
            // ...
        }
    }